我正在使用 python
requests
并执行 post
import requests
response = requests.post('https://petdogs.net/search/?input=abcdefgh',
headers=HEADERS,
allow_redirects=False)
print(response.headers)
这些是
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
但是当我这样做时
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'}
并且
location
缺失
我看到了一些谈到的答案
'Access-Control-Expose-Headers': 'Location'
但我不知道它是否正确和/或如何正确使用它。
我也尝试过使用
urllib
import urllib.request as urllib2
>>> f = urllib2.urlopen('https://petdogs.net/search/?input=abcdefgh')
>>> print(f.headers)
但这会回应
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
如何获取
location
的值?
解决办法很简单。 这个“位置”响应头是一个重定向。 python request 模块试图让事情变得更简单 所以它会尝试自动重新编码您。 所以你只需添加“allow_redirects”参数并将其设置为False即可。
(请求方式不重要)
示例:
import requests
res = requests.get("example.com", allow_redirects=False)
print(res.headers)
输出:
{'Content-Length': '0', 'location': 'your stuff here'}
from urllib import request, parse
def create_post():
payload = {'title':'Pyton Requests','body':'Requests are qwesome','userId':1}
data = parse.urlencode(payload).encode()
response = request.Request('https://jsonplaceholder.typicode.com/posts', data)
resp = request.urlopen(response)
print(resp.headers['Location'])
def main():
# """ Main entry point of the app """
# print("hello world")
create_post()
if __name__ == "__main__":
""" This is executed when run from the command line """
main()
我用这个方法来获取位置,但在我的输出中没有位置
导入请求
res = requests.get("example.com",allow_redirects=False) 打印(res.headers)