Python 请求库重定向新的 url

新手上路,请多包涵

我一直在查看 Python Requests 文档,但看不到我想要实现的任何功能。

在我的脚本中,我正在设置 allow_redirects=True

我想知道该页面是否已重定向到其他内容,新 URL 是什么。

例如,如果起始 URL 是: www.google.com/redirect

最终的 URL 是 www.google.co.uk/redirected

我如何获得该网址?

原文由 Daniel Pilch 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 271
1 个回答

您正在查找 请求历史记录

response.history 属性是指向最终 URL 的响应列表,可以在 response.url 中找到。

 response = requests.get(someurl)
if response.history:
    print("Request was redirected")
    for resp in response.history:
        print(resp.status_code, resp.url)
    print("Final destination:")
    print(response.status_code, response.url)
else:
    print("Request was not redirected")

演示:

 >>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
...     print(resp.status_code, resp.url)
...
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get

原文由 Martijn Pieters 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题