美文网首页Python小哥哥
Python:Requests模块的异常值处理

Python:Requests模块的异常值处理

作者: 我爱学python | 来源:发表于2019-05-27 20:39 被阅读80次

用Python的requests模块进行爬虫时,一个简单高效的模块就是requests模块,利用get()或者post()函数,发送请求。

但是在真正的实际使用过程中,我们可能会遇到网络的各种变化,可能会导致请求过程发生各种未知的错误导致程序中断,这就使我们的程序不能很好的去处理错误。所以为了使我们的程序在请求时遇到错误,可以捕获这种错误,就要用到try…except方法,以及了解requests可能发生的各种错误.

以下是request.exceptions下的各种异常错误:

RequestException:

HTTPError(RequestException)

UnrewindableBodyError(RequestException)

RetryError(RequestException)

ConnectionError(RequestException) ProxyError(ConnectionError)

SSLError(ConnectionError)

ConnectTimeout(ConnectionError, Timeout)

Timeout(RequestException) ReadTimeout

URLRequired(RequestException)

TooManyRedirects(RequestException)

MissingSchema(RequestException, ValueError)

InvalidSchema(RequestException,ValueError)

InvalidURL(RequestException,ValueError)

InvalidHeader(RequestException,ValueError)

ChunkedEncodingError(RequestException)

StreamConsumedError(RequestException,TypeError)

ContentDecodingError(RequestException,BaseHTTPError)

在实际应用的过程中,我们可以把请求放在try下,把可能发生的异常用except获取:

官方异常处理文档:http://www.python-requests.org/en/master/_modules/requests/exceptions/

相关文章

网友评论

    本文标题:Python:Requests模块的异常值处理

    本文链接:https://www.haomeiwen.com/subject/dtvktctx.html