爬虫request模块异常处理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/86029384

一 URLError

1 代码 

'''
URLError类来自urllib库的error模块,它继承自OSError类,是error异常模块的基类,
由request模块生的异常都可以通过捕获URLError类来处理。
它具有一个属性reason,即返回错误的原因。
'''
from urllib import request, error
try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
    print(e.reason)

2 运行结果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/3_1_2.py
Not Found

3 说明

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

二 HTTPError

1 点睛

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

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

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

  • headers:返回请求头。

2 实战一代码

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')
3 实战一结果

3 实战一结果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/3_1_2.py
Not Found
404
Server: nginx/1.10.3 (Ubuntu)
Date: Mon, 07 Jan 2019 13:32:06 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/"

4 实战一说明

依然是同样的网址,这里捕获了HTTPError异常,输出了reason、code和headers属性。

5 实战二代码

'''
因为URLError是HTTPError的父类,所以可以先选择捕获子类的错误,再去捕获父类的错误
这样就可以做到先捕获HTTPError,获取它的错误状态码、原因、headers等信息。
如果不是HTTPError异常,就会捕获URLError异常,输出错误原因。
最后,用else来处理正常的逻辑。这是一个较好的异常处理写法。
'''
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')
except error.URLError as e:
    print(e.reason)
else:
    print('Request Successfully')

6 实战二运行结果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/3_1_2.py
Not Found
404
Server: nginx/1.10.3 (Ubuntu)
Date: Mon, 07 Jan 2019 13:36:21 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/"

7 实战三代码

'''
有时候,reason属性返回的不一定是字符串,也可能是一个对象。
这里我们直接设置超时时间来强制抛出timeout异常
'''
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')

8 实战三运行结果

E:\WebSpider\venv\Scripts\python.exe E:/WebSpider/3_1_2.py
<class 'socket.timeout'>
TIME OUT

9 实战三说明

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

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/86029384
今日推荐