无法从 HTTP 请求 python 获取 header 位置

Can't get header location from HTTP request python

我想获取 python 中 header 位置的值。

当我使用 requests 时,GET 请求基本上 header 没有 Location

headers = {"content-type": "application/json", "Accept-Charset": "UTF-8"}

result = requests.get('https://forms.is.yail18.com/laptop', headers=headers, verify=False)
location = result.headers
print(location)

{'Date': 'Thu, 24 Feb 2022 14:59:48 GMT', 'Server': 'Apache', 'X-Powered-By': 'PHP/7.2.24', 'Expires': 'Thu, 19 Nov 1981 08:52:00 GMT', 'Cache-Control': 'no-store, no-cache, must-revalidate', 'Pragma': 'no-cache', 'Content-Length': '3158', 'Content-Type': 'text/html; charset=UTF-8', 'Keep-Alive': 'timeout=15, max=99', 'Connection': 'Keep-Alive'}

当我使用 urllib2 时,它具有相同的行为。 header 没有 Location

f = urllib2.urlopen('https://forms.is.yail18.com/laptop')
print(f.headers)

Date: Thu, 24 Feb 2022 14:42:40 GMT
Server: Apache
X-Powered-By: PHP/7.2.24
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Length: 3158
Content-Type: text/html; charset=UTF-8
Set-Cookie: form=bc32f147d42e975793f6890c7d7b3377; path=/
Connection: close

当我使用从 shell 执行的 curl 命令时,它 return 是正确的内容。

curl -v 'https://forms.is.yail18.com/laptop'
...
skipped
...
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Date: Thu, 24 Feb 2022 14:21:50 GMT
< Server: Apache
< X-Powered-By: PHP/7.2.24
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate
< Pragma: no-cache
< Location: https://forms.is.yail18.com/laptop/c88a74d100985529b1644c217d2c92bf
< Content-Length: 0
< Content-Type: text/html; charset=UTF-8
< Set-Cookie: form=c0072bd1510a149f613e3b6bca3086db; path=/

所以我的问题是,如何在不使用 shell 的情况下获取对 python 中 header 位置的 return 请求?

requests 自动跟随响应中的重定向。您正在查看的响应 object 是对第二个请求的答复,它不包含位置 header。您可能想通过将 allow_redirects=False 传递给 requests.get()

来禁用此功能