繁体   English   中英

如何在urllib.urlretrieve中捕获404错误

[英]How to catch 404 error in urllib.urlretrieve

背景:我正在使用urllib.urlretrieve ,而不是urllib*模块中的任何其他函数,因为钩子函数支持(参见下面的reporthook )..它用于显示文本进度条。 这是Python> = 2.6。

>>> 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错误处理的最着名的方法是什么?

查看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以检测http_error_default

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)

你应该使用:

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)

编辑:这里的基本原理是,除非你期望异常状态,它是一个例外,它可能发生,你可能甚至没有想到它 - 所以,而不是让你的代码继续运行,而不成功,默认行为 - 非常合理 - 禁止其执行。

URL Opener对象的“retreive”方法支持reporthook并在404上引发异常。

http://docs.python.org/library/urllib.html#url-opener-objects

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM