Answers:
您正在寻找请求历史记录。
该response.history
属性是导致最终到达网址的响应列表,可以在中找到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
这回答了一个稍有不同的问题,但是由于我自己一直坚持这个问题,所以我希望它对其他人可能有用。
如果要使用allow_redirects=False
并直接到达第一个重定向对象,而不是遵循它们的链,而只想直接从302响应对象中获取重定向位置,则r.url
则将无法使用。相反,它是“ Location”标头:
r = requests.get('http://github.com/', allow_redirects=False)
r.status_code # 302
r.url # http://github.com, not https.
r.headers['Location'] # https://github.com/ -- the redirect destination
r.next
什么吗?我认为应该包含PreparedRequest
指向重定向URL 的指向,但事实并非如此……
该文档具有以下内容:https: //requests.readthedocs.io/zh/master/user/quickstart/#redirection-and-history
import requests
r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for
我觉得requests.head代替requests.get会更安全的处理URL重定向时调用,检查GitHub的问题在这里:
r = requests.head(url, allow_redirects=True)
print(r.url)
urllib2