httplib没有获得所有重定向代码

时间:2011-05-28 00:34:14

标签: python httplib

我正在尝试获取一个似乎不止一次重定向的网页的最终网址。在浏览器中试用此示例网址,并将其与我的代码段底部的最终网址进行比较:

Link that redirects more than once

这是我运行的测试代码,请注意,获取代码200的最终URL与浏览器中的代码不同。我有什么选择?

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 个答案:

答案 0 :(得分: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()

答案 1 :(得分:3)

您可以尝试将User-Agent标头设置为浏览器的User-Agent。

PS: 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