How to set and retrieve cookie in HTTP header in Python?(如何在 Python 的 HTTP 标头中设置和检索 cookie?)
问题描述
我需要从服务器发送的 HTTP 响应中获取 cookie,并将其放入下一个请求的标头中.我该怎么做?
I need to get the cookies from a HTTP response sent by a server and put it in the next request's header. How can I do it?
提前致谢.
推荐答案
你应该使用 cookielib 模块 与 urllib.
You should use the cookielib module with urllib.
它将在请求之间存储 cookie,您可以在磁盘上加载/保存它们.这是一个例子:
It will store cookies between requests, and you can load/save them on disk. Here is an example:
import cookielib
import urllib2
cookies = cookielib.LWPCookieJar()
handlers = [
urllib2.HTTPHandler(),
urllib2.HTTPSHandler(),
urllib2.HTTPCookieProcessor(cookies)
]
opener = urllib2.build_opener(*handlers)
def fetch(uri):
req = urllib2.Request(uri)
return opener.open(req)
def dump():
for cookie in cookies:
print cookie.name, cookie.value
uri = 'http://www.google.com/'
res = fetch(uri)
dump()
res = fetch(uri)
dump()
# save cookies to disk. you can load them with cookies.load() as well.
cookies.save('mycookies.txt')
请注意,NID
和 PREF
的值在请求之间是相同的.如果您省略了 HTTPCookieProcessor
,这些将有所不同(urllib2 不会在第二次请求中发送 Cookie
标头).
Notice that the values for NID
and PREF
are the same between requests. If you omitted the HTTPCookieProcessor
these would be different (urllib2 wouldn't send Cookie
headers on the 2nd request).
这篇关于如何在 Python 的 HTTP 标头中设置和检索 cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 的 HTTP 标头中设置和检索 cookie?


- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01