我试着用谷歌查找,我发现没有例子,我尝试了堆栈溢出我发现主题是有帮助但最后它没有给我所需的结果。 我想要做的是从PHP脚本“http://127.0.0.1/web/accounts/login.php”创建一个cookie,它用[user] => dwaik保存一个cookie,我试着从另一个php脚本“http://127.0.0.1/web/accounts/read_cookie.php”中读取该cookie。它成功地读了!问题是我用python使用代码
无法读取它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,但是我推出了login.php表单谷歌浏览器并从IE,帮助将不胜感激
答案 0 :(得分:0)
已有类似的主题。请看这里:Retrieving all Cookies in Python
答案 1 :(得分:0)
我建议你使用机械化。
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
你可以参观一本精心准备的机械化表格。 http://www.pythonforbeginners.com/cheatsheet/python-mechanize-cheat-sheet
我希望这个有所帮助。