本文学习内容来自:https://germey.gitbooks.io/python3webspider/content/
urllib库中有URLError类,request模块产生的错误都可以通过捕获这个类进行处理
URLErroe若是发生错误了就会返回一个reason,就是错误原因
URLError有个专门处理HTTP请求错误的子类,叫做HTTPError
有三个属性:
1code,返回Http状态码
2reason,返回错误原因
3headers,返回request的headers
错误处理的代码:
from urllib import request,error
try:
response=request.urlopen('http://cuiqingcai.com/index.com')
except error.HTTPError as e:
print(e.reason,e.code,e.headers,seq=' ')
except error.URLError as e:
print(e.reason)
else:
print('Request successfully!')