- 请求教程
- 请求 - 主页
- 请求 - 概述
- 请求 - 环境设置
- 请求 - Http 请求如何工作?
- 请求 - 处理请求
- 处理 HTTP 请求的响应
- 请求 - HTTP 请求标头
- 请求 - 处理 GET 请求
- 处理 POST、PUT、PATCH 和 DELETE 请求
- 请求 - 文件上传
- 请求 - 使用 Cookie
- 请求 - 处理错误
- 请求 - 处理超时
- 请求 - 处理重定向
- 请求 - 处理历史记录
- 请求 - 处理会话
- 请求 - SSL 认证
- 请求 - 身份验证
- 请求 - 事件挂钩
- 请求 - 代理
- 请求 - 使用请求进行网页抓取
- 请求有用的资源
- 请求 - 快速指南
- 请求 - 有用的资源
- 请求 - 讨论
请求 - 处理会话
要维护请求之间的数据,您需要会话。因此,如果同一主机被多次调用,您可以重用 TCP 连接,从而提高性能。现在让我们看看如何在使用会话发出的请求之间维护 cookie。
使用会话添加cookie
import requests
req = requests.Session()
cookies = dict(test='test123')
getdata = req.get('https://httpbin.org/cookies',cookies=cookies)
print(getdata.text)
输出
E:\prequests>python makeRequest.py
{
"cookies": {
"test": "test123"
}
}
使用会话,您可以跨请求保留 cookie 数据。还可以使用会话传递标头数据,如下所示 -
例子
import requests
req = requests.Session()
req.headers.update({'x-user1': 'ABC'})
headers = {'x-user2': 'XYZ'}
getdata = req.get('https://httpbin.org/headers', headers=headers)
print(getdata.headers)