如何在Python中设置和获取HTTP头中的cookie?
我需要从服务器发送的HTTP响应中获取cookies,然后把它放到下一个请求的头部里。请问我该怎么做呢?
提前谢谢你。
4 个回答
4
你可以在 Python 2.7 中使用
url="http://google.com"
request = urllib2.Request(url)
sock=urllib2.urlopen(request)
cookies=sock.info()['Set-Cookie']
content=sock.read()
sock.close()
print (cookies, content)
然后在发送请求的时候
def sendResponse(cookies):
import urllib
request = urllib2.Request("http://google.com")
request.add_header("Cookie", cookies)
request.add_data(urllib.urlencode([('arg1','val1'),('arg1','val1')]))
opener=urllib2
opener=urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
sock=opener.open(request)
content=sock.read()
sock.close()
print len(content)
15
看看urllib模块:
(在Python 3.1中使用,在Python 2中,使用urllib2.urlopen)
用来获取cookies:
>>> import urllib.request
>>> d = urllib.request.urlopen("http://www.google.co.uk")
>>> d.getheader('Set-Cookie')
'PREF=ID=a45c444aa509cd98:FF=0:TM=14.....'
而发送cookies时,只需在请求中添加一个Cookie头。像这样:
r=urllib.request.Request("http://www.example.com/",headers={'Cookie':"session_id=1231245546"})
urllib.request.urlopen(r)
补充:
“http.cookie”(在Python 2中是“Cookie”)可能对你更有效:
25
你应该使用 cookielib模块 来配合 urllib 使用。
这个模块可以在不同的请求之间保存 cookies,而且你还可以把它们存到硬盘上。下面是一个例子:
import cookielib
import urllib2
cookies = cookielib.LWPCookieJar()
handlers = [
urllib2.HTTPHandler(),
urllib2.HTTPSHandler(),
urllib2.HTTPCookieProcessor(cookies)
]
opener = urllib2.build_opener(*handlers)
def fetch(uri):
req = urllib2.Request(uri)
return opener.open(req)
def dump():
for cookie in cookies:
print cookie.name, cookie.value
uri = 'http://www.google.com/'
res = fetch(uri)
dump()
res = fetch(uri)
dump()
# save cookies to disk. you can load them with cookies.load() as well.
cookies.save('mycookies.txt')
注意,在不同的请求中,NID
和 PREF
的值是一样的。如果你不使用 HTTPCookieProcessor
,那么这些值就会不同(因为 urllib2 在第二次请求时不会发送 Cookie
头信息)。