httplib is not getting all the redirect codes

杀马特。学长 韩版系。学妹 提交于 2019-12-04 16:58:38

you can try to set your User-Agent header to the User-Agent of your browser.

ps: urllib2 automatically redirects

EDIT:

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

You can use HttpLib2 to get the actual location of an 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)

Execution looks like this:

$ python2.7 getContentLocation.py
http://keyinvest.podcaster.de/8uhr30.rss

Note this example also uses caching (which is not supported neither by urllib nor by httplib). So this will run repeatedly significantly faster. This might be interesting for crawling/scraping. If you do not want caching, replace h = httplib2.Http(".cache_httplib") with h = httplib2.Http().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!