csatblogspotdotcom

Monday, December 19, 2016

关于python官网urllib2实例的问题

python官网Docs有介绍urllib2,里面有实例,对于python2.7版本,页面是: https://docs.python.org/2/howto/urllib2.html 在“Wrapping it Up”这一节,有number1和number2两个例子,其中第二个例子有些问题: if拦截了URLError,后面的elif永远不会执行,因为e永远有reason值,如果是普通URLError,reason就是给出的描述,如果是HTTPError(属于URLError里面一个子集),那么print出来是“OK”,所以如果是有URLError,hasattr(e, 'reason')总是成立,轮不到后面的elif部分执行;应该像前面的number1一样调整下顺序,先处理HTTPError再考虑URLError。 附: 下面是原文档: Wrapping it Up So if you want to be prepared for HTTPError or URLError there are two basic approaches. I prefer the second approach. Number 1 from urllib2 import Request, urlopen, URLError, HTTPError req = Request(someurl) try: response = urlopen(req) except HTTPError as e: print 'The server couldn\'t fulfill the request.' print 'Error code: ', e.code except URLError as e: print 'We failed to reach a server.' print 'Reason: ', e.reason else: # everything is fine Note The except HTTPError must come first, otherwise except URLError will also catch an HTTPError. Number 2 from urllib2 import Request, urlopen, URLError req = Request(someurl) try: response = urlopen(req) except URLError as e: if hasattr(e, 'reason'): print 'We failed to reach a server.' print 'Reason: ', e.reason elif hasattr(e, 'code'): print 'The server couldn\'t fulfill the request.' print 'Error code: ', e.code else: # everything is fine

Labels: , , , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home