Python Requests library redirect new url
阿新 • • 發佈:2018-12-23
我想去猜演唱會門票的購買URL, 使用 requests 來判斷 url 是否存在,遇到 server side 會使用 http code 302 來 redirect.
解法:
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"
Demo:
>>> 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