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

p4rjhz4m  于 2021-08-25  发布在  Java
关注(0)|答案(1)|浏览(423)

我正在使用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` ?
w80xi6nr

w80xi6nr1#

使用urllib,这是很简单的。

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()

相关问题