How to Retrieve Redirect History in Python Requests?

Barbara Streisand
Release: 2024-11-11 04:42:03
Original
693 people have browsed it

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")
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template