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")
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
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!