如何使用 Python 检查 url 是否重定向到另一个 url [英] How to check if the url redirect to another url using Python

查看:60
本文介绍了如何使用 Python 检查 url 是否重定向到另一个 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想检查目标网址在访问后是否会被重定向.我以为我可以做这样的事情:

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

但它不起作用,因为即使 url 重定向,我仍然得到 200.有人可以帮我解决这个问题吗?

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

推荐答案

只是详细说明我的评论:

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

这篇关于如何使用 Python 检查 url 是否重定向到另一个 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆