我怎样才能在python脚本中接受cookie?
试试这个:
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
它应该打印
Currently have 0 cookies ... Currently have 2 cookies
(谷歌总是设置一个cookie).除非您想将cookie保存到磁盘并在以后使用它,否则您并不需要这么多.你应该找到
urllib2.build_opener(HTTPCookieProcessor).open(url)
照顾你想要的大部分东西.
更多信息:
HTTPCookieProcessor
比如build_opener
FileCookieJar
Urllib2 - 失踪的maual
最简单的方法是使用请求库.
import requests url = 'http://www.google.com/doodles/' r = requests.get(url) print r.cookies