Python – How do I make a URL request using Python and return the URL to which I am redirected?

How do I make a URL request using Python and return the URL to which I am redirected?… here is a solution to the problem.

How do I make a URL request using Python and return the URL to which I am redirected?

I’m trying to access a URL that will return a code string in the redirected URL.

Example: https://exampleurl.com

After 2-3 seconds I was redirected to https://newurl.com/stuffhere?code=97412098512yidfh480b14r

Is there a way to return a new URL?

Solution

From official docs :

The Response.history list contains the Response objects that were
created in order to complete the request. The list is sorted from the
oldest to the most recent response.

Here is an example of printing a URL to the final URL:

import requests
response = requests.get('http://httpbin.org/redirect/3')
for resp in response.history:
    print(resp.url)

To get only the final URL, you just have to do the following:

print(response.url)

Related Problems and Solutions