python网络爬虫学习笔记(四):异常处理

urllib的error模块定义了由request模块产生的异常。如果出现了问题,request模块便会抛出error模块中定义的异常。

1.URLError

URLError类来自urllib库的error模块,它继承自OSError类,是error异常模块的基类,由request模块生的异常都可以通过捕获这个类来处理。

它具有一个属性reason,即返回错误的原因。

下面用一个实例来看一下:

from urllib import request,error
try:
    response = request.urlopen("http://cuiqingcai.com/index.htm")
except error.URLError as e:
    print(e.reason)
Not Found

程序没有直接报错,而是输出了如上内容,这样通过如上操作,我们就可以避免程序异常终止,同时异常得到了有效处理。

2.HTTPError

它是URLError的子类,专门用来处理HTTP请求错误,比如认证请求失败等。它有如下3个属性。

code:返回HTTP状态码,比如404表示网页不存在,500表示服务器内部错误等。

reason:同父类一样,用于返回错误的原因。

headers:返回请求头。

from urllib import request,error
try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
    print(e.reason, e.code, e.headers, sep='\n')
Not Found
404
Server: nginx/1.10.3 (Ubuntu)
Date: Wed, 23 Sep 2020 12:41:57 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: close
Vary: Cookie
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Link: <https://cuiqingcai.com/wp-json/>; rel="https://api.w.org/"


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

扫描二维码关注公众号,回复: 11844692 查看本文章
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):
        print('TIME OUT')
<class 'socket.timeout'>
TIME OUT

这里我们直接设置超时时间来强制抛出timeout异常。

可以发现,reason属性的结果是socket.timeout类。所以,这里我们可以用isinstance()方法来判断它的类型,作出更详细的异常判断。

猜你喜欢

转载自blog.csdn.net/qq_43328040/article/details/108766542
今日推荐