Python 多次发送 GET 请求,使用不同 Cookie 和 Authorization
如何使用 Python 发送多个 GET 请求,使用不同的 Cookie 和 Authorization
在某些情况下,你可能需要向同一个 API 发送多个 GET 请求,但每个请求都需要使用不同的 Cookie 和 Authorization。这可以通过 Python 代码实现。
示例代码
以下代码展示了如何将不同的 Cookie 和 Authorization 存储在一个列表中,然后使用循环遍历列表中的值,每次更换 headers 中的 Cookie 和 Authorization,再发送请求。
import requests
url = 'https://hotel.wanzhuhu.com/guns-cloud-branch/signIn/signIn?branchId=10769&weekId='
cookies = [
'cookie1',
'cookie2',
'cookie3'
]
authorizations = [
'authorization1',
'authorization2',
'authorization3'
]
for i in range(len(cookies)):
headers = {
'Host': 'hotel.wanzhuhu.com',
'Connection': 'keep-alive',
'cookie': cookies[i],
'charset': 'utf-8',
'content-type': 'application/json;charset=utf-8',
'User-Agent': 'Mozilla/5.0 (Linux; Android 7.1.2; JEF-AN00 Build/N2G47H; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/86.0.4240.99 XWEB/3263 MMWEBSDK/20220105 Mobile Safari/537.36 MMWEBID/3599 MicroMessenger/8.0.19.2080(0x28001337) Process/appbrand0 WeChat/arm64 Weixin NetType/WIFI Language/zh_CN ABI/arm64 MiniProgramEnv/android',
'authorization': authorizations[i],
'Accept-Encoding': 'gzip,compress,br,deflate',
'Referer': 'https://servicewechat.com/wxd0b0b4a5f0d0537f/130/page-frame.html'
}
response = requests.get(url, headers=headers)
print(response.content.decode('utf-8'))
解释
- 定义变量: 首先定义了目标 URL、Cookie 列表和 Authorization 列表。
- 循环遍历: 使用
for循环遍历 Cookie 和 Authorization 列表。 - 构建请求头: 在循环中,每次都使用当前的 Cookie 和 Authorization 来构建请求头。
- 发送请求: 使用
requests.get()函数发送 GET 请求,并将请求头传递给headers参数。 - 打印响应: 打印服务器返回的响应内容。
注意事项
- 确保 Cookie 和 Authorization 的格式正确,并与 API 的要求一致。
- 如果需要发送 POST 请求,请使用
requests.post()函数。 - 为了提高效率,可以考虑使用多线程或多进程来并行发送多个请求。
通过以上方法,你可以轻松地使用不同的 Cookie 和 Authorization 发送多个 GET 请求,并根据需要进行调整。
原文地址: https://www.cveoy.top/t/topic/mLOu 著作权归作者所有。请勿转载和采集!