如何用Python读取cookies
我试着在谷歌上查找这个问题,但没有找到例子。我在Stack Overflow上也找了相关话题,虽然有些内容对我有帮助,但最后还是没能得到我想要的结果。
我想做的是通过一个PHP脚本创建一个cookie,链接是 "http://127.0.0.1/web/accounts/login.php",它能保存一个cookie,内容是[user]=>dwaik。我尝试从另一个PHP脚本 "http://127.0.0.1/web/accounts/read_cookie.php" 读取这个cookie,结果成功读取了!问题是,我用Python的代码却无法读取这个cookie。
from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib
cj = cookielib.CookieJar()
opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())
req = Request("http://127.0.0.1/web/accounts/login.php")
f = opener.open(req)
print "the cookies are: "
for cookie in cj:
print cookie
这段代码是从 Retrieving all Cookies in Python 上找到的,但它无法读取我的cookie。不过,我是通过谷歌浏览器和IE打开login.php的,希望能得到一些帮助。
1 个回答
0
我建议你使用 mechanize 这个工具。
import cookielib
import urllib2
import mechanize
br = mechanize.Browser()
cookiejar = cookielib.LWPCookieJar()
br.set_cookiejar( cookiejar )
br.set_proxies({"http": "yourProxyHereIfneeded","https":
"yourProxyHereIfneeded"})
br.set_handle_equiv( True )
br.set_handle_gzip( True )
br.set_handle_redirect( True )
br.set_handle_referer( True )
br.set_handle_robots( False )
br.set_handle_refresh( mechanize._http.HTTPRefreshProcessor(),
max_time = 1)
br.addheaders = [ ( 'User-agent', 'yourHeadervalueifNeeded' ) ]
#this one will open you what your desired domain
response = br.open("theDomain")
#and this one stands for saving the cookies for you.
cookiejar.save('cookies.txt', ignore_discard=True,
ignore_expires=True)
#after you saved your cookie a txt or dump with pickle for example.
#You can easly load it while configure the browser Object at the start
#our example code.
br = mechanize.Browser()
cookiejar = cookielib.LWPCookieJar()
cookiejar.load('cookie_login.txt', ignore_discard=True,
ignore_expires=True)
br.set_cookiejar( cookiejar )
想了解更多信息,可以访问 http://wwwsearch.sourceforge.net/mechanize/doc.html#dealing-with-bad-html
另外,这里有一个很好的 mechanize 使用小抄,你可以去看看:http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet
希望这些对你有帮助。