如何在不知道名称的情况下用 Python 读回所有 cookie?
不确定这是否是您正在寻找的内容,但这是一个简单的示例,您将 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
将
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]
这可能正是您正在寻找的。
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)
查看您获得的 HTTP 响应中的
Cookie:
标头,使用标准库中的模块 Cookie
解析其内容。
2024 / Python 3.11+ 的更新答案,使用 HTTPSConnection/HTTPResponse
from http.client import HTTPResponse
def get_response_cookies(http_response: HTTPResponse):
cookie_list = http_response.headers.get_all("set-cookie")
if cookie_list is None or len(cookie_list) == 0:
return None
cookies = {}
for cookie_str in cookie_list:
cookie_info = cookie_str.split("; ")
[name, val] = cookie_info[0].split("=")
cookies[name] = val
return cookies
您只需在连接请求的 HttpResponse 结果上调用此函数即可:
from http.client import HTTPSConnection
connection = HTTPSConnection(host)
connection.request(method=req_method, url=path_url, body=body, headers=headers)
response = connection.getresponse()
cookies = get_response_cookies(response)