Python 请求模块 - 获取响应 cookies

问题描述 投票:0回答:4

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

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

r.cookies['example_cookie_name']

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

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

谢谢

cookies python-3.x module request response
4个回答
20
投票

您可以迭代地检索它们:

import requests

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

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

3
投票

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

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

2
投票

我从这里得到了以下代码:

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

看看这是否适合您。


0
投票

您现在可以通过以下方式获取所有响应 cookie 的

dict

response.cookies.get_dict()
© www.soinside.com 2019 - 2024. All rights reserved.