python-3.x - 当 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)
解决方案
基本上你需要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/
推荐阅读
- javascript - d3 fitSize 不符合使用 geojson 多边形的预期范围
- html - 控制器未在 index.html 上的 HTMLInputElement.onclick 中定义
- flutter - 在 DataTable 构建器中将 Map 转换为 List 的多个问题
- debian - Debian Buster 上的“设备上没有剩余空间”错误,/dev/sda1 100% Full
- hyperlink - 如何解决灯塔的代码问题“AVADA WordPress 主题”问题
- html - 如何让 2 个悬停效果同时工作?
- python - URL 在浏览器中有效,但在使用 requests.get 方法时无效
- docker - 如何在本地网络中使用 traefik 和 docker 设置子域?
- eclipse - 无法使用与 Gradle 分发版“https://services.gradle.org/distributions/gradle-6.8.1-all.zip”的连接来运行分阶段构建操作
- r - 如何在 R 中的函数中使用参数创建新变量名?