2

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

多次重定向的链接

这是我正在运行的测试代码,请注意获得代码 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 
4

2 回答 2

5

您可以使用HttpLib2获取 URL 的实际位置:

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().

于 2012-07-23T17:54:07.823 回答
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
于 2011-05-28T00:39:15.080 回答