Home > Backend Development > Python Tutorial > How can I get the final URL after redirects using Python Requests?

How can I get the final URL after redirects using Python Requests?

DDD
Release: 2024-11-13 02:06:02
Original
915 people have browsed it

How can I get the final URL after redirects using Python Requests?

Retrieving Redirected URLs with Python Requests

Requests, a popular Python library for sending HTTP requests, allows users to handle redirects by setting the allow_redirects parameter to True. While this resolves the issue of automatic redirects, it leaves you unaware of the target URL. This question addresses how to obtain the final URL after a series of redirects.

The solution lies in the response.history attribute. After a successful request, response.url returns the final URL, while response.history provides a list of all intermediate responses and their respective URLs. Using this data, you can inspect the redirects and determine the final destination.

The following code snippet demonstrates this approach:

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

This code checks if the response.history attribute is not empty, indicating the occurrence of redirects. Each resp object in the history contains the status code and URL of an intermediate response. Finally, response.url provides the final URL.

Consider the following example:

>>> import requests
>>> response = requests.get('http://httpbin.org/redirect/3')
>>> response.history
(<Response [302]>, <Response [302]>, <Response [302]>)
>>> for resp in response.history:
...     print(resp.status_code, resp.url)
... 
302 http://httpbin.org/redirect/3
302 http://httpbin.org/redirect/2
302 http://httpbin.org/redirect/1
>>> print(response.status_code, response.url)
200 http://httpbin.org/get
Copy after login

This output confirms that the request was redirected three times before reaching the final destination at http://httpbin.org/get, providing a complete picture of the redirect chain.

The above is the detailed content of How can I get the final URL after redirects using 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template