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

gag*_*ina 6 python redirect urllib urllib2

我写了这个函数:

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()
Run Code Online (Sandbox Code Playgroud)

此函数将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
Run Code Online (Sandbox Code Playgroud)

但它似乎不起作用..

谢谢

小智 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')
Run Code Online (Sandbox Code Playgroud)