当urlopen请求出现问题时会出现URLError,HTTPError是URLError的子类。
URLError包含一个"reason"属性,是一条出错信息。
HTTPError:包含这些属性:url, code, msg, hdrs, fp。
当判断是URLError还是HTTPError异常时,只要判断是否有reason或者code属性就行。
下面是检测异常的代码,hasattr是内建的函数,用来判断对象时候包含给定的属性。
import urllib2
req = urllib2.Request('http://bbs.youkuaiyun.com/callmewhy')
try:
response = urllib2.urlopen(req)
except urllib2.URLError, 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:
print 'No exception was raised.'
转载于:https://blog.51cto.com/liuping0906/1399532