我有一個bash腳本,它使用cookie登錄並保存URL中的文本文件。我需要使用Mechanize在Python中實現同樣的功能,但是我無法實現它。這只是兩行bash,它讓我發瘋。我看過Mechanize文檔,但無法找到如何去做。我怎樣才能接受和發送餅乾與機械化?
#!/bin/sh
base_url=https://myapp.url.com
sign_on_request="aK8Rj_mrVk3J-PDf9x6...LONG KEY...4ZPMd0w"
# Login
wget -q --keep-session-cookies --save-cookies savedcookie.txt --post-data="sign_on_request=$sign_on_request" -O - $base_url/login > /dev/null 2>&1
# Save CSV
wget -q --load-cookies savedcookie.txt -O output.txt $base_url/data
這裏是我的嘗試:
import mechanize
import cookielib
# Browser
br = mechanize.Browser()
# Cookie Jar
cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)
# Login
req = mechanize.Request("https://myapp.url.com/login", "sign_on_request=aK8Rj_mrVk3J-PDf9x6...LONG KEY...4ZPMd0w")
cj.add_cookie_header(req)
res = mechanize.urlopen(req)
# Download
f = br.retrieve('https://myapp.url.com/data')[0]
print f