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?
基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
