Mridang Agarwalla Mridang Agarwalla - 1 year ago 152
Python Question

How can I get the final redirect URL when using urllib2.urlopen?

I'm using the

method to open a URL and fetch the markup of a webpage. Some of these sites redirect me using the 301/302 redirects. I would like to know the final URL that I've been redirected to. How can I get this?

Answer Source

Call the .geturl() method of the file object returned. Per the urllib2 docs:

geturl() — return the URL of the resource retrieved, commonly used to determine if a redirect was followed


>>> import urllib2
>>> response = urllib2.urlopen('')
>>> response.geturl()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download