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

淺唱寂寞╮ 提交于 2019-12-11 06:14:01

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/43423203/how-to-check-if-the-url-redirect-to-another-url-using-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!