gpt4 book ai didi

python - httplib 未获取所有重定向代码

转载 作者:行者123 更新时间:2023-11-28 20:28:11 27 4
gpt4 key购买 nike

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

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

最佳答案

您可以使用 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()

关于python - httplib 未获取所有重定向代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6158895/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com