欢迎访问宙启技术站
智能推送

Python中requests.exceptions的错误处理指南

发布时间:2023-12-25 03:46:07

在Python中,requests库是一个常用的HTTP库,用于发送HTTP请求和处理HTTP响应。requests库使用HTTP协议与服务器进行通信,并且提供了丰富的接口和函数来处理各种HTTP操作。

在使用requests库时,可能会遇到一些网络错误或HTTP错误。requests库为这些错误定义了一系列异常类,存储在requests.exceptions模块中。正确地处理这些异常是编写健壮和可靠的代码的重要组成部分。在本文中,我们将介绍requests库中一些常见的异常,并提供相应的处理和示例。

1. requests.exceptions.RequestException

RequestException是所有其他requests库异常的基类。它表示发生了一个请求相关的错误。在实际的代码中,我们通常将它用作其他具体异常的基类。

示例:

   import requests
   from requests.exceptions import RequestException

   try:
       response = requests.get('http://www.example.com')
       response.raise_for_status()
   except RequestException as e:
       print('请求异常:', str(e))
   

2. requests.exceptions.ConnectionError

ConnectionError表示与服务器建立连接时发生的错误,例如DNS查询失败、拒绝连接等。

示例:

   import requests
   from requests.exceptions import ConnectionError

   try:
       response = requests.get('http://www.example.com')
       response.raise_for_status()
   except ConnectionError as e:
       print('连接异常:', str(e))
   

3. requests.exceptions.Timeout

Timeout表示请求超时的异常。当请求在指定的时间内没有得到响应时,将引发此异常。

示例:

   import requests
   from requests.exceptions import Timeout

   try:
       response = requests.get('http://www.example.com', timeout=0.01)
       response.raise_for_status()
   except Timeout:
       print('请求超时')
   

4. requests.exceptions.HTTPError

HTTPError表示HTTP请求返回了错误的响应。这通常是在服务器返回4xx或5xx状态码时引发的异常。

示例:

   import requests
   from requests.exceptions import HTTPError

   try:
       response = requests.get('http://www.example.com')
       response.raise_for_status()
   except HTTPError as e:
       print('HTTP错误:', str(e))
   

5. requests.exceptions.TooManyRedirects

TooManyRedirects表示重定向次数过多的异常。当请求被重定向的次数超过requests库的默认最大重定向次数时,将引发此异常。

示例:

   import requests
   from requests.exceptions import TooManyRedirects

   try:
       response = requests.get('http://www.example.com', allow_redirects=True, max_redirects=5)
       response.raise_for_status()
   except TooManyRedirects:
       print('重定向次数过多')
   

以上是requests库中一些常见的异常及其处理方式。在实际的代码中,我们应该对可能的异常进行适当的处理,以避免程序意外终止,并为用户提供有关错误的友好提示。