Requests 简明教程

Requests - Working with Errors

This chapter will discuss how to deal with errors coming down when working with the Http request library. It is always a good practice to have errors managed for all possible cases.

Error Exception

requests 模块会发出以下类型的错误异常:

ConnectionError - 当任何连接错误时会引发此异常。例如,网络失败、DNS 错误,因此 Request 库会引发 ConnectionError 异常。

HTTPError − 基于状态代码,例如 401、404,将为请求的 URL 引发 HTTPError。

这种错误将为请求产生的无效响应而引发。

此错误因请求的 URL 超时而引发。

如果超出最大重定向次数,将引发 TooManyRedirects 错误。

Example

以下是如何显示超时错误的示例 −

import requests
getdata =
requests.get('https://jsonplaceholder.typicode.com/users',timeout=0.001)
print(getdata.text)

Output

raise ConnectTimeout(e, request=request)
requests.exceptions.ConnectTimeout:
HTTPSConnectionPool(host='jsonplaceholder.ty
picode.com', port=443): Max retries exceeded with url: /users (Caused
by Connect
TimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at
0x000000B02AD
E76A0>, 'Connection to jsonplaceholder.typicode.com timed out. (connect
timeout = 0.001)'))