我有以下情况。我从 3 个来源发送请求(postman、cURL 和 python requests 库)。对于 Postman 和 cURL,我收到相同的响应,但对于 python requests 库,我得到不同的响应,我不明白其中的区别:
在 Postman 中,我发送的请求没有 cookie,也没有跟随重定向。所有请求都使用来自同一台机器的相同 IP 地址。
版本:
卷曲
curl 8.6.0 (x86_64-apple-darwin23.0) libcurl/8.6.0 (SecureTransport) LibreSSL/3.3.6 zlib/1.2.12 nghttp2/1.61.0
Python
Python 3.7 请求 2.25.1
操作系统
macOS 14.5 (x64)
cURL 命令
curl --location '<URL>' \
--header 'host: <HOST>' \
--header 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36' \
--header 'Accept-Encoding: gzip, deflate' \
--compressed > test.html
Python 请求代码
import requests
url = "<URL>"
payload = {}
headers = {
'host': '<HOST>',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
'Accept-Encoding': 'gzip, deflate'
}
response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
我尝试检查所有这些方法都使用哪种http协议,我发现它们都使用HTTP 1.1
我不明白这些方法(cURL 和 requests)之间有什么区别,所以我收到不同的响应。
在 Postman 中,我发送的请求没有 cookie 且没有跟随 重定向。
请求的默认行为是遵循重定向,您可以通过使用allow_redirects来指示请求不要这样做
import requests
r = requests.get("http://www.example.com", allow_redirects=False)