如何检查urllib2是否遵循重定向?

时间:2011-12-07 11:29:04

标签: python redirect urllib2 urllib

我写了这个函数:

def download_mp3(url,name):
        opener1 = urllib2.build_opener()
        page1 = opener1.open(url)
        mp3 = page1.read()
        filename = name+'.mp3'
        fout = open(filename, 'wb')
        fout.write(mp3)
        fout.close()

此函数将url和名称都作为字符串。 然后将从url下载并保存一个名为变量名称的mp3。

网址的格式为http://site/download.php?id=xxxx,其中xxxx是mp3的ID

如果此ID不存在,则网站会将我重定向到另一个页面。

所以,问题是:我如何检查这个id是否存在?我试图检查url是否存在这样的函数:

def checkUrl(url):
    p = urlparse(url)
    conn = httplib.HTTPConnection(p.netloc)
    conn.request('HEAD', p.path)
    resp = conn.getresponse()
    return resp.status < 400

但它似乎不起作用..

谢谢

2 个答案:

答案 0 :(得分:5)

像这样,并检查代码:

import urllib2, urllib

class NoRedirectHandler(urllib2.HTTPRedirectHandler):
    def http_error_302(self, req, fp, code, msg, headers):
        infourl = urllib.addinfourl(fp, headers, req.get_full_url())
        infourl.status = code
        infourl.code = code
        return infourl
    http_error_300 = http_error_302
    http_error_301 = http_error_302
    http_error_303 = http_error_302
    http_error_307 = http_error_302

opener = urllib2.build_opener(NoRedirectHandler())
urllib2.install_opener(opener)
response = urllib2.urlopen('http://google.com')
if response.code in (300, 301, 302, 303, 307):
    print('redirect')

答案 1 :(得分:2)

我对此的回答看起来像

req = urllib2.Request(url)
try:
   response = urllib2.urlopen(url)
except urllib2.HTTPError as e:
   # Do something about it
   raise HoustonWeHaveAProblem
else:
   if response.url != url:
       print 'We have redirected!'