How to get the URL of a redirect with Python How to get the URL of a redirect with Python python python

How to get the URL of a redirect with Python


You can easily get D by just asking for the current URL.

req = urllib2.Request(starturl, datagen, headers)res = urllib2.urlopen(req)finalurl = res.geturl()

To deal with the intermediate redirects you'll probably need to build your own opener, using HTTPRedirectHandler that records the redirects.


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


For Python 3, the solution with urllib is much simpler:

import urllibdef resolve(url):    return urllib.request.urlopen(url).geturl()