首页 > Web开发 > 详细

urllib.request模块(2):处理异常

时间:2020-12-02 23:24:46      阅读:80      评论:0      收藏:0      [点我收藏+]

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)#属性reason,用来返回错误的原因

运行结果:输出Not Found

 

2.HTTPError

它是URLError的子类,专门用来处理HTTP请求错误。

它有三个属性:

code:返回HTTP状态码,比如404表示页面不存在。

reason:返回错误的原因。

headers:返回请求头。

 

捕获HTTPError异常,输出code,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)

运行结果:

技术分享图片

 

又由于URLError是HTTPError的父类,所以可以先选择捕获子类的错误,再去捕获父类的错误。所以更好的写法如下。

代码:

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)
#如果不是HTTPError异常,就会捕获URLError异常
else: print(Request Successfully)
#否则无异常

 

有时reason属性返回的不一定是字符串,也可能是一个对象。

代码:

import socket
import urllib.request
import urllib.error

try:
    response=urllib.request.urlopen(https://www.baidu.com,timeout=0.01)
except urllib.error.URLError as e:
    print(type(e.reason))
    if isinstance(e.reason,socket.timeout):#用isinstance()方法来判断reason的类型
        print(TIME OUT)

运行结果:输出

<class ‘socket.timeout‘>
TIME OUT

可以看出reason属性的结果是socket.timeout类。

 

参考用书《python3网络爬虫开发实战》

urllib.request模块(2):处理异常

原文:https://www.cnblogs.com/Alone-haoran/p/14076548.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!