Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a URL request with Python and return the URL I am redirected to?

I am trying to go to a URL, which will return a code string in the redirected url.

Example: https://exampleurl.com

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

Is there a way to return the the new URL?

like image 627
Kusnan Avatar asked Oct 14 '25 03:10

Kusnan


1 Answers

From the 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's an example that prints the URLs that led to the final URL:

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

To get the final URL only, you can simply do:

print(response.url)
like image 151
glhr Avatar answered Oct 16 '25 17:10

glhr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!