Python请求模块 - 获取响应cookie

nom*_*cle 5 cookies module response request python-3.x

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

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

r.cookies['example_cookie_name']
Run Code Online (Sandbox Code Playgroud)

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

<<class 'requests.cookies.RequestsCookieJar'>[]>
Run Code Online (Sandbox Code Playgroud)

谢谢

Dan*_*San 9

您可以迭代检索它们:

import requests

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

for c in r.cookies:
    print(c.name, c.value)
Run Code Online (Sandbox Code Playgroud)


Dom*_*aft 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
Run Code Online (Sandbox Code Playgroud)

看看这是否适合你。