Home  >  Article  >  Backend Development  >  How to Retrieve Redirect History in Python Requests?

How to Retrieve Redirect History in Python Requests?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 04:42:03703browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn