【问题标题】:How to catch the redirected urls with urllib2 in python如何在python中使用urllib2捕获重定向的url
【发布时间】:2012-12-18 15:43:01
【问题描述】:

我正在使用 urllib2 模块来读取一个 html 页面,下面是我的代码

code.py

import urllib2, httplib

httplib.HTTPConnection.debuglevel = 1  
request = urllib2.Request("http://www.vodafone.in/Pages/tuesdayoffers_che.aspx")
opener = urllib2.build_opener()
f = opener.open(request)
print f.url

结果

'http://www.vodafone.in/pages/tuesdayoffers_che.aspx?cid=che'

当我在浏览器中给出上面的 url 时,它被重定向到 http://www.vodafone.in/pages/home_che.aspx?cid=che,但是从上面的代码中我得到了相同的给定 url

最后如何使用 urrlib2 捕获重定向的 url 并从中读取数据,因为 我有许多 url 将被重定向到其他一些 url,最后我的意图是捕获重定向的 url 并从捕获的 url 中读取数据,那么如何在 python 中使用urllib2 and httplib

实现这一点

【问题讨论】:

标签: python url redirect urllib2 httplib


【解决方案1】:

是的,@Sp 是对的,这个网页是由 javascript 重定向的。以下为页面来源。

<script>document.write("<meta http-equiv=\"refresh\" content=\"3;url=/pages/home_che.aspx\">");</script>

一种方法是使用正则表达式来提取重定向位置。喜欢url\=([a-z_./]*)

>>> import re
>>> p = re.compile(r'url\=([a-z_./]*)')
>>> p.findall(r'''<script>document.write("<meta http-equiv=\"refresh\"content=\"3;url=/pages/home_che.aspx\">");</script>''')
['/pages/home_che.aspx']

【讨论】:

    【解决方案2】:

    不需要正则表达式。该站点正在通过 JavaScript 重定向,但是仍然返回 302 状态代码。您可以通过以下方式验证这一点:

    url = 'http://www.vodafone.in/Pages/tuesdayoffers_che.aspx'
    file_pointer = urllib2.urlopen(url)
    print file_pointer.getcode()
    

    当返回 302 状态码时,响应标头中有一个 Location 标头。您可以通过以下方式查看:

    url = 'http://www.vodafone.in/Pages/tuesdayoffers_che.aspx'
    file_pointer = urllib2.urlopen(url)
    print file_pointer.info()
    

    记录Location 网址。这将是您被重定向到的页面。

    【讨论】:

      猜你喜欢
      • 2013-03-11
      • 1970-01-01
      • 2013-08-06
      • 2011-04-22
      • 2011-01-23
      • 2019-03-11
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多