httplib未能获取所有重定向代码
我正在尝试获取一个页面的最终网址,这个页面似乎会进行多次重定向。你可以在浏览器中试试这个示例网址,然后和我代码片段底部的最终网址进行对比:
这是我运行的测试代码,注意最终返回状态码为200的网址和你在浏览器中看到的并不一样。我还有哪些选择呢?
Python 2.7.1+ (r271:86832, Apr 11 2011, 18:13:53)
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import httplib
>>> from urlparse import urlparse
>>> url = 'http://www.usmc.mil/units/hqmc/'
>>> host = urlparse(url)[1]
>>> req = ''.join(urlparse(url)[2:5])
>>> conn = httplib.HTTPConnection(host)
>>> conn.request('HEAD', req)
>>> resp = conn.getresponse()
>>> print resp.status
301
>>> print resp.msg.dict['location']
http://www.marines.mil/units/hqmc/
>>> url = 'http://www.marines.mil/units/hqmc/'
>>> host = urlparse(url)[1]
>>> req = ''.join(urlparse(url)[2:5])
>>> conn = httplib.HTTPConnection(host)
>>> conn.request('HEAD', req)
>>> resp = conn.getresponse()
>>> print resp.status
302
>>> print resp.msg.dict['location']
http://www.marines.mil/units/hqmc/default.aspx
>>> url = 'http://www.marines.mil/units/hqmc/default.aspx'
>>> host = urlparse(url)[1]
>>> req = ''.join(urlparse(url)[2:5])
>>> conn = httplib.HTTPConnection(host)
>>> conn.request('HEAD', req)
>>> resp = conn.getresponse()
>>> print resp.status
200
>>> print resp.msg.dict['location']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'location'
>>> print url
http://www.marines.mil/units/hqmc/default.aspx //THIS URL DOES NOT RETURN A 200 IN ANY BROWSER I HAVE TRIED
2 个回答
5
你可以使用 HttpLib2 来获取一个网址的实际位置:
import httplib2
def getContentLocation(link):
h = httplib2.Http(".cache_httplib")
h.follow_all_redirects = True
resp = h.request(link, "GET")[0]
contentLocation = resp['content-location']
return contentLocation
if __name__ == '__main__':
link = 'http://podcast.at/podcast_url344476.html'
print getContentLocation(link)
执行的过程看起来是这样的:
$ python2.7 getContentLocation.py
http://keyinvest.podcaster.de/8uhr30.rss
注意,这个例子还使用了缓存(而 urllib 和 httplib 都不支持缓存)。所以这样运行会快很多,特别适合用来抓取网页。如果你不想使用缓存,可以把 h = httplib2.Http(".cache_httplib")
替换成 h = httplib2.Http()
。
3
你可以试着把你的用户代理(User-Agent)设置成你浏览器的用户代理。
补充说明:
urllib2会自动进行重定向。
编辑:
In [2]: import urllib2
In [3]: resp = urllib2.urlopen('http://www.usmc.mil/units/hqmc/')
In [4]: resp.geturl()
Out[4]: 'http://www.marines.mil/units/hqmc/default.aspx