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?


基础教程推荐
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01