Home >Backend Development >Python Tutorial >How to Extract Redirected URLs Using Python Requests Library?

How to Extract Redirected URLs Using Python Requests Library?

DDD
DDDOriginal
2024-11-12 12:40:02957browse

How to Extract Redirected URLs Using Python Requests Library?

Python Requests Library: Accessing Redirected URL

In Python Requests library, you can access the final redirected URL through the response.url attribute. However, if you want to retrieve the complete list of redirects that led to the final destination, you need to use the response.history attribute.

The response.history attribute is a list of responses that represent each step of the redirection process. Each element in the list is a Response object, containing the status code and the URL of the corresponding redirection.

To access the original request URL, you can access the first element in the response.history list, while the final destination URL is available in response.url.

Here's a code snippet demonstrating how to access both the original and final URLs:

import requests

response = requests.get(some_url, allow_redirects=True)

if response.history:
    # Request was redirected
    print("Request was redirected:")
    for resp in response.history:
        print("-", resp.status_code, resp.url)

# Final destination URL
print("Final destination:")
print("-", response.status_code, response.url)

The above is the detailed content of How to Extract Redirected URLs Using Python Requests Library?. 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