在Python中接受Cookie [英] Accept Cookies in Python
本文介绍了在Python中接受Cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Python脚本中接受Cookie?
解决方案
尝试:
import urllib2
import cookielib
jar = cookielib.FileCookieJar(cookies)
opener = urllib2.build_opener (urllib2.HTTPCookieProcessor(jar))
print目前有%d个Cookie%len(jar)
print获取页面
response = opener.open ://google.com)
print response.headers
printGot page
print目前有%d个Cookie%len(jar)
打印jar
它应该打印
目前有0个cookie
...
目前有2个cookie
(Google始终设置Cookie)。你真的不需要这么多,除非你想保存你的cookie到磁盘,以后使用它们。您应该会发现
urllib2.build_opener(HTTPCookieProcessor).open(url)
更多信息:
How can I accept cookies in a python script?
解决方案
Try this:
import urllib2
import cookielib
jar = cookielib.FileCookieJar("cookies")
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
print "Currently have %d cookies" % len(jar)
print "Getting page"
response = opener.open("http://google.com")
print response.headers
print "Got page"
print "Currently have %d cookies" % len(jar)
print jar
It should print
Currently have 0 cookies
...
Currently have 2 cookies
(Google always sets a cookie). You don't really need this much unless you want to save your cookies to disk and use them later. You should find that
urllib2.build_opener(HTTPCookieProcessor).open(url)
Takes care of most of what you want.
More info here:
这篇关于在Python中接受Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文