pythonurllib2http-redirect

How to check if the url redirect to another url using Python


I want to check whether the target url will be redirected after visiting. I thought I could do something like this:

req = urllib2.Request(url=url, headers=headers)
resp = urllib2.urlopen(req, timeout=3)
code = resp.code
if code == '200': # valid
else: # not valid

But it does not work since even if the url redirects, I still get 200. Can anyone help me with this plz?


Solution

  • Just to elaborate on my comment:

    req = urllib2.Request(url=url, headers=headers)
    resp = urllib2.urlopen(req, timeout=3)
    redirected = resp.geturl() != url # redirected will be a boolean True/False