2009-08-20 84 views
25

背景:我使用urllib.urlretrieve,而不是urllib*模块中的任何其他功能,因为支持钩子函数(请参阅下面的reporthook)..它用于显示文本进度条。这是Python> = 2.6。如何捕捉404错误urllib.urlretrieve

>>> urllib.urlretrieve(url[, filename[, reporthook[, data]]]) 

然而,urlretrieve是如此哑它叶无道检测到HTTP请求的状态(例如:它是404或200?)。

>>> fn, h = urllib.urlretrieve('http://google.com/foo/bar') 
>>> h.items() 
[('date', 'Thu, 20 Aug 2009 20:07:40 GMT'), 
('expires', '-1'), 
('content-type', 'text/html; charset=ISO-8859-1'), 
('server', 'gws'), 
('cache-control', 'private, max-age=0')] 
>>> h.status 
'' 
>>> 

什么是最有名的下载方式与钩状支持远程HTTP文件(以显示进度条)和体面的HTTP错误处理?

+0

在您的请求中未提供HTTP状态应该可能被认为是stdlib中的错误(但请查看下面更好的库,请求) – 2016-03-17 20:37:48

回答

27

退房urllib.urlretrieve的完整代码:

def urlretrieve(url, filename=None, reporthook=None, data=None): 
    global _urlopener 
    if not _urlopener: 
    _urlopener = FancyURLopener() 
    return _urlopener.retrieve(url, filename, reporthook, data) 

换句话说,你可以用urllib.FancyURLopener(它的公共urllib的API的一部分)。您可以覆盖http_error_default检测404:

class MyURLopener(urllib.FancyURLopener): 
    def http_error_default(self, url, fp, errcode, errmsg, headers): 
    # handle errors the way you'd like to 

fn, h = MyURLopener().retrieve(url, reporthook=my_report_hook) 
+0

我不想指定处理程序;它是否会抛出像urllib2.urlopen这样的异常? – 2009-08-20 21:14:40

+4

让它很容易扔掉。 FancyURLopener子类抛出的URLopener,所以你可以尝试调用基类的实现:def http_error_default(...):URLopener.http_error_default(...) – orip 2009-08-20 21:35:26

+0

这是一个非常好的解决方案,我现在就自己使用它。 – 2010-01-02 22:34:29

14

例外,您应该使用:

import urllib2 

try: 
    resp = urllib2.urlopen("http://www.google.com/this-gives-a-404/") 
except urllib2.URLError, e: 
    if not hasattr(e, "code"): 
     raise 
    resp = e 

print "Gave", resp.code, resp.msg 
print "=" * 80 
print resp.read(80) 

编辑:这里的基本原理是,除非你期望特殊的st吃了,它是一个例外,你可能甚至都没有考虑过 - 所以不是让你的代码在不成功的时候继续运行,而是默认的行为 - 相当明智 - 禁止它的运行执行。

+2

钩状支持? – 2010-02-05 16:02:52

+1

Sridhar,请参阅http://stackoverflow.com/a/9740603/819417 – 2012-03-16 16:07:36