Home > Backend Development > Python Tutorial > How Do I Determine the Final URL After Redirection Using Python Requests?

How Do I Determine the Final URL After Redirection Using Python Requests?

Susan Sarandon
Release: 2024-11-11 12:32:02
Original
993 people have browsed it

How Do I Determine the Final URL After Redirection Using Python Requests?

Determining New URL After Redirection with Python Requests Library

The Python Requests library excels at handling HTTP requests, but understanding its redirection mechanism is crucial for accessing the final landing page. By setting allow_redirects=True, the library follows requests through a redirect chain. However, to obtain the new, redirected URL, you need to dive deeper into the request's history.

The response.history attribute holds a record of all redirection responses encountered during the request. Each response in the history list contains its status code and the URL it redirected to. The last item in the list represents the final destination, which is stored in response.url.

To access this information, employ the following code:

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

Consider the following example:

>>> 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 demonstration showcases the process of following the redirect chain, presenting the status codes and URLs of each redirection, and ultimately displaying the final destination. By utilizing response.history, you can effortlessly extract the new URL after a request has been redirected.

The above is the detailed content of How Do I Determine the Final URL After Redirection 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template