【问题标题】:How to check if the url redirect to another url using Python如何使用 Python 检查 url 是否重定向到另一个 url
【发布时间】:2017-09-11 09:39:03
【问题描述】:

我想检查目标url在访问后是否会被重定向。我以为我可以这样做:

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。有人可以帮我解决这个问题吗?

【问题讨论】:

  • resp.geturl() 会给你最终的 url。您可以将原始网址与最终网址进行比较并检测重定向。
  • req = urllib2.Request(starturl, datagen, headers) res = urllib2.urlopen(req) finalurl = res.geturl()

标签: python urllib2 url-redirection


【解决方案1】:

只是为了详细说明我的评论:

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

【讨论】:

    猜你喜欢
    • 2012-07-22
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-07
    相关资源
    最近更新 更多