python异常处理篇
方法1
#们抓取网页一般需要对 headers(网页头信息)进行模拟,这时候需要使用到 urllib.request.Request
from urllib.urllib import Request,urlopen
from urllib.error import URLError,HTTPError
req = Request(url)
try:
response = urlopen(req)
except HTTPError as c:
print('The server couldn\'t fulfill the request.')
print('Error code:',c.code) #c.code 返回状态码
# print('Error read'c.read()) #HTTPErroe会返回一个页面可以用c.read()将它打印出来
except URLError as c:
print('We failed to reach a server.')
print('Reason:',c.reason)
else:
#Things are going first-rate
关于URLError 和HTTPError
1、HTTPError是URLError的一个子类
2、先写URLError再写HTTPError的话HTTPError会被拦截而不执行
3、reason是URLError的一个属性,code是HTTPError一个属性
方法2(推荐)
from urllib.urllib import Request,urlopen
from urllib.error import URLError
req = Request(url)
try:
response = urlopen(req)
except URLError as u:
if hasattr(u,'reason'):
print('We failed to reach a server.')
print('Reason:',u.reason)
elif hasattr(u,'code'):
print('The server couldn\'t fulfill the request.')
print('Error code:',u.code)
else:
#Things are going first-rate
解惑
1、为什么import不调用HTTPError:HTTPError是URLError的一个子类
2、hasattr是什么:hasattr() 函数用于判断对象是否包含对应的属性。
用法:
hasattr(object, name)
参数:
object -- 对象
name -- 字符串,属性名。
返回值:
如果对象有该属性返回 True,否则返回 False。