Python Requests库重定向新url [英] Python Requests library redirect new url
问题描述
我一直在浏览Python Requests文档,但是我看不到任何我想要实现的功能。
I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve.
在我的脚本中,我设置 allow_redirects = True
。
In my script I am setting allow_redirects=True
.
我想知道该页面是否已被重定向到其他内容,新URL是什么。
I would like to know if the page has been redirected to something else, what is the new URL.
例如,如果起始网址为: www.google.com/redirect
For example, if the start URL was: www.google.com/redirect
最终网址为 www.google.co。英国/重定向
如何获取该网址?
推荐答案
您正在寻找请求历史记录。
response.history
属性是导致最终结果的回复列表URL,可在 response.url
中找到。
The response.history
attribute is a list of responses that led to the final URL, which can be found in 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
这篇关于Python Requests库重定向新url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!