在Python中接受Cookies

10 python cookies

我怎样才能在python脚本中接受cookie?

Tom*_*ham 19

试试这个:

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
Run Code Online (Sandbox Code Playgroud)

它应该打印

Currently have 0 cookies
...
Currently have 2 cookies
Run Code Online (Sandbox Code Playgroud)

(谷歌总是设置一个cookie).除非您想将cookie保存到磁盘并在以后使用它,否则您并不需要这么多.你应该找到

urllib2.build_opener(HTTPCookieProcessor).open(url)
Run Code Online (Sandbox Code Playgroud)

照顾你想要的大部分东西.

更多信息:


Gal*_*cha 6

最简单的方法是使用请求库.

import requests
url = 'http://www.google.com/doodles/'
r = requests.get(url)
print r.cookies
Run Code Online (Sandbox Code Playgroud)


Can*_*der 3

您可能想看看cookielib