[英]How to catch the redirected urls with urllib2 in python
我正在使用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中读取数据,那么如何使用urllib2 and httplib
在python中实现这一点
正则表达式不是必需的。 该网站正在通过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
URL。 这将是您被重定向到的页面。
是的,@ 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']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.