如何检查 urllib2 是否遵循重定向? [英] how to check if the urllib2 follow a redirect?

查看:64
本文介绍了如何检查 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()

这个函数将一个 url 和一个名字都作为字符串.然后将从 url 中下载并保存一个 mp3,名称为变量名.

This function take an url and a name both as string. Then will download and save an mp3 from the url with the name of the variable name.

网址采用 http://site/download.php?id=xxxx 形式,其中 xxxx 是mp3的id

the url is in the form http://site/download.php?id=xxxx where xxxx is the id of an mp3

如果此 ID 不存在,该站点会将我重定向到另一个页面.

if this id does not exist the site redirects me to another page.

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

So, the question is: how Can I check if this id exist? I've tried to check if the url exist with a function like this:

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

但它似乎不起作用..

谢谢

推荐答案

类似这样的,并检查代码:

Something like this, and check code:

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')

这篇关于如何检查 urllib2 是否遵循重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆