Search code examples
pythonhttp-redirecturllib2

How to get the URL of a redirect with Python


In Python, I'm using urllib2 to open a url. This url redirects to another url, which redirects to yet another url.

I wish to print out the url after each redirect.

For example

-> = redirects to

A -> B -> C -> D

I want to print the URL of B, C and D (A is already known because it's the start URL).


Solution

  • Probably the best way is to subclass urllib2.HTTPRedirectHandler. Dive Into Python's chapter on redirects may be helpful.