8

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

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

r.cookies['example_cookie_name']

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

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

谢谢

4

3 回答 3

12

您可以迭代地检索它们:

import requests

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

for c in r.cookies:
    print(c.name, c.value)
于 2014-12-03T17:32:08.893 回答
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

看看这是否适合你。

于 2013-09-29T23:37:30.800 回答
1

Cookies 也存储在标头中。如果这对您不起作用,请检查您的标题:

"Set-Cookie: Name=Value; [Expires=Date; Max-Age=Value; Path=Value]"
于 2019-07-12T17:43:16.293 回答