Rei*_*ica 28 python url http urllib
背景:我正在使用urllib.urlretrieve,而不是urllib*模块中的任何其他功能,因为钩子功能支持(见reporthook下文)..用于显示文本进度条.这是Python> = 2.6.
>>> urllib.urlretrieve(url[, filename[, reporthook[, data]]])
Run Code Online (Sandbox Code Playgroud)
但是,它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
''
>>>
Run Code Online (Sandbox Code Playgroud)
下载具有类似钩子支持的远程HTTP文件(显示进度条)和一个不错的HTTP错误处理的最着名的方法是什么?
ori*_*rip 28
看看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)
Run Code Online (Sandbox Code Playgroud)
换句话说,您可以使用urllib.FancyURLopener(它是公共urllib API的一部分).您可以覆盖http_error_default以检测404s:
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)
Run Code Online (Sandbox Code Playgroud)
ler*_*son 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)
Run Code Online (Sandbox Code Playgroud)
编辑:这里的基本原理是,除非你期望异常状态,它是一个例外,它可能发生,你可能甚至没有想到它 - 所以,而不是让你的代码继续运行,而不成功,默认行为 - 非常合理 - 禁止其执行.
| 归档时间: |
|
| 查看次数: |
23819 次 |
| 最近记录: |