Source From Here
Question
I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve. In my script I am setting allow_redirects=True. I would like to know if the page has been redirected to something else, what is the new URL.
For example, if the start URL was: www.google.com/redirect
And the final URL is www.google.co.uk/redirected
How do I get that URL?
How-To
You are looking for the request history. The response.history attribute is a list of responses that led to the final URL, which can be found in response.url:
A real demo as below:
Question
I've been looking through the Python Requests documentation but I cannot see any functionality for what I am trying to achieve. In my script I am setting allow_redirects=True. I would like to know if the page has been redirected to something else, what is the new URL.
For example, if the start URL was: www.google.com/redirect
And the final URL is www.google.co.uk/redirected
How do I get that URL?
How-To
You are looking for the request history. 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"
沒有留言:
張貼留言