Home > Article > Backend Development > How to Retrieve Redirect History in Python Requests?
Redirecting URLs in Python Requests
In Python's Requests library, setting allow_redirects=True allows the library to automatically follow HTTP redirects. However, it doesn't provide a direct way to retrieve the new URL after redirection.
To access the redirect history, you can leverage the response.history attribute. This attribute contains a list of Response objects representing each redirect that occurred before reaching the final URL, which is available in response.url.
Here's an example code snippet:
import requests response = requests.get(someurl, allow_redirects=True) 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")
The above is the detailed content of How to Retrieve Redirect History in Python Requests?. For more information, please follow other related articles on the PHP Chinese website!