从 python 请求中的response.headers获取位置

raj*_*247 2 python urllib response-headers python-requests

我正在使用 pythonrequests并做一个post

import requests  
response = requests.post('https://petdogs.net/search/?input=abcdefgh', 
headers=HEADERS, 
allow_redirects=False)

print(response.headers)
Run Code Online (Sandbox Code Playgroud)

这些是我可以在浏览器的开发人员工具中看到的标头中的值response,我想获取其值location

content-language: en-gb
content-length: 0
content-type: text/html; charset=utf-8
date: Wed, 07 Jul 2021 17:44:52 GMT
location: /product/id=12345/
server: nginx/1.14.0 (Ubuntu)
vary: Accept-Language, Cookie, Origin
x-content-type-options: nosniff
x-frame-options: DENY
Run Code Online (Sandbox Code Playgroud)

但当我这样做时,print(response.headers)我只看到这个

{'Server': 'nginx/1.14.0 (Ubuntu)', 'Date': 'Wed, 07 Jul 2021 18:23:45 GMT',
'Content-Type': 'text/html', 'Transfer-Encoding': 'chunked', 'Connection': 'keep-alive',
 'X-Frame-Options': 'DENY', 'Vary': 'Accept-Language, Origin', 
'Content-Language': 'en', 'X-Content-Type-Options': 'nosniff', 'Content-Encoding': 'gzip'}
Run Code Online (Sandbox Code Playgroud)

并且 location失踪了

我看到几个回答都谈到了

'Access-Control-Expose-Headers': 'Location'
Run Code Online (Sandbox Code Playgroud)

但我不知道它是否正确和/或如何正确使用它。

我也尝试过使用urllib

import urllib.request as urllib2
>>> f = urllib2.urlopen('https://petdogs.net/search/?input=abcdefgh')
>>> print(f.headers)
Run Code Online (Sandbox Code Playgroud)

但这回应了

Server: nginx/1.14.0 (Ubuntu)
Date: Thu, 08 Jul 2021 11:12:58 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 128053
Connection: close
X-Frame-Options: DENY
Vary: Cookie, Accept-Language, Origin
Content-Language: en
X-Content-Type-Options: nosniff
Set-Cookie: csrftoken=xxxxxx; expires=Thu, 07 Jul 2022 11:12:57 GMT; Max-Age=31449600; Path=/; SameSite=Lax
Set-Cookie: sessionid=bbbbbb; expires=Thu, 22 Jul 2021 11:12:57 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax
Run Code Online (Sandbox Code Playgroud)

我如何获得 的值 location

小智 6

解决方案很简单。这个“位置”响应头是一个重定向。python 请求模块试图让事情变得更简单,所以它会尝试自动重新引导你。因此,您只需添加“allow_redirects”参数并将其设置为 False 即可。

(请求方法应该不重要)

例子:

import requests

res = requests.get("example.com", allow_redirects=False)
print(res.headers)
Run Code Online (Sandbox Code Playgroud)

输出:

{'Content-Length': '0', 'location': 'your stuff here'}

Run Code Online (Sandbox Code Playgroud)