如何在不知道名字的情况下回读Python中的所有cookie?
答案 0 :(得分:24)
不确定这是否是您正在寻找的,但这里有一个简单的例子,您可以将Cookie放入cookiejar并阅读它们:
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
答案 1 :(得分:4)
查看您获得的HTTP响应中的Cookie:
标头,使用标准库中的模块Cookie
解析其内容。
答案 2 :(得分:4)
将os.environ['HTTP_COOKIE']
放入数组:
#!/usr/bin/env python
import os
if 'HTTP_COOKIE' in os.environ:
cookies = os.environ['HTTP_COOKIE']
cookies = cookies.split('; ')
handler = {}
for cookie in cookies:
cookie = cookie.split('=')
handler[cookie[0]] = cookie[1]
答案 3 :(得分:4)
这可能正是您所寻找的。 p>
Python 3.4
import requests
r = requests.get('http://www.about.com/')
c = r.cookies
i = c.items()
for name, value in i:
print(name, value)