28

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).

  • 2
    why not use the requests module, actualURL = requests.head(passedurl, timeout=100.0 , headers={'Accept-Encoding': 'identity'}).headers.get('location', passedurl) ? – Ciasto piekarz Jul 26 '14 at 17:47
9

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

45

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.

  • 6
    Doesn't really answer the question though, right? – sberry Feb 4 '11 at 20:27
  • 2
    It solves the more common question of "what is the url I arrived to"? – Ángel Sep 26 '14 at 9:13
  • 2
    here is a similar answer using requests: stackoverflow.com/a/20475712/309483 – Janus Troelsen Nov 10 '15 at 11:23

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.