首页 > 解决方案 > 当 cookie 不时更改时发送 http 请求

问题描述

我在使用 python 发送 http 请求时遇到了一些麻烦,因为 http 标头中的 cookie 会不时地自动更改。

如何通过检查 http 请求捕获软件来发送 http 请求而不更改 cookie?

我通常发送这样的请求:

import requests as req
url = "somesite.com"
headers = {"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"}
resp = req.get(url , headers=headers)
print(resp.text)

标签: python-3.xcookiespython-requests

解决方案


基本上你需要requests.Session它自动处理cookies。

这是一个示例代码尝试:

from requests import Session

# create session object
session = Session()
session.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36'


# do requests now
url = "somesite.com"
resp = session.get(url)

请查看文档:https ://requests.readthedocs.io/en/latest/user/advanced/


推荐阅读