第一种:直接捕获URLError类 可直接返回错误的原因
代码:from urllib import request , error
try:
response = request.urlopen('http://gujiass.com/index.htm')
except error.URLError as e :
print(e.reason)
第二种:特定的HTTPError子类专门用来处理HTTP请求错误,其中有三个属性
1.code:
返回http状态码 eg: 404---网页不存在 500---服务器内部出错
2.reason:
返回错误原因
3.headers:
返回requset headers(请求头)
代码:from urllib import request , error
try:
response = request.urlopen('http://gujiass.com/index.htm')
except error.HTTPError as e :
print(e.reason , e.code, e.headers ,sep = '\n')
#改进:先捕获子类再捕获父类的错误
from urllib import request , error
try:
response = request.urlopen('http://gujiass.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')