Python请求模块 - 获取响应cookie

时间:2013-09-29 14:49:25

标签: cookies python-3.x module request response

我正在使用python 3.3和请求模块。我正在尝试了解如何从响应中检索cookie。请求文档说:

url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)

r.cookies['example_cookie_name']

这没有意义,如果您还不知道cookie的名称,如何从cookie中获取数据?也许我不明白饼干是如何工作的?如果我尝试打印响应cookie,我会得到:

<<class 'requests.cookies.RequestsCookieJar'>[]>

由于

3 个答案:

答案 0 :(得分:8)

您可以迭代检索它们:

import requests

r = requests.get('http://example.com/some/cookie/setting/url')

for c in r.cookies:
    print(c.name, c.value)

答案 1 :(得分:2)

我从HERE获得了以下代码:

from urllib2 import Request, build_opener, HTTPCookieProcessor, HTTPHandler
import cookielib

#Create a CookieJar object to hold the cookies
cj = cookielib.CookieJar()
#Create an opener to open pages using the http protocol and to process cookies.
opener = build_opener(HTTPCookieProcessor(cj), HTTPHandler())

#create a request object to be used to get the page.
req = Request("http://www.about.com")
f = opener.open(req)

#see the first few lines of the page
html = f.read()
print html[:50]

#Check out the cookies
print "the cookies are: "
for cookie in cj:
    print cookie

看看这是否适合你。

答案 2 :(得分:0)

Cookie也存储在标题中。如果这不适合您,请检查标题:

"Set-Cookie: Name=Value; [Expires=Date; Max-Age=Value; Path=Value]"