#处理异常,urllib的error模块定义了由requeat模块产生的异常。
1.URLError类来自urllib库的error模块,由request模块产生的异常都可以通过捕获这个类来处理
from urllib import request,error
try:
response = request.urlopen(‘https://cuiqingcai.com/index.htm’)
except error.URLError as e:
print(e.reason)
#URLError里的属性reason返回错误的原因
#2.HTTPError是URLError的子类,专门用来处理HTTP请求错误,比如认证请求失败。
#属性一:code:返回HTTP状态码,200为正常,404网页不存在,500服务器内部错误
#属性二:reason 同父类一样,用于返回错误的原因
#属性三:headers 返回请求头,实例如下
from urllib import request,error
try:
response = request.urlopen(‘https://cuiqingcai.com/index.htm’)
except error.HTTPError as e:
print(e.reason,e.code,e.headers,sep=’\n’)
except error.URLError as e:
print(e.reason)
else:
print(‘Request Successfully’)
#先捕获HTTPError,获取它的错误状态码,原因,headers等信息。如不是捕获URLError异常,最后用else来处理正常的逻辑
import socket
import urllib.request
import urllib.error
try:
response = urllib.request.urlopen(‘https://www.baidu.com’,timeout=0.01)
except urllib.URLError as e:
print(type(e.reason))
if isinstance(e.reason,socket.timeout):#用isinstance()方法来判断它的类型,做出更详细的异常判断
print(‘TIME OUT’)