Python中requests.exceptions的使用方法
发布时间:2023-12-25 03:44:49
在Python中,requests.exceptions模块提供了一些异常类,用于处理与requests库相关的异常情况。这些异常类可以帮助我们更好地了解和处理错误。下面是requests.exceptions的使用方法和一些使用例子:
1. requests.exceptions.RequestException:所有requests库的异常都是从该基类继承的。可以用于捕获所有requests库可能引发的异常。
import requests
from requests.exceptions import RequestException
try:
response = requests.get('https://www.example.com')
response.raise_for_status()
except RequestException as e:
print("An error occurred:", str(e))
2. requests.exceptions.HTTPError:当请求返回一个不成功的状态码(非200-299)时,会引发该异常。
import requests
from requests.exceptions import HTTPError
try:
response = requests.get('https://www.example.com/not_found')
response.raise_for_status()
except HTTPError as e:
print("An HTTP error occurred:", str(e))
3. requests.exceptions.ConnectionError:当请求发生连接错误时,会引发该异常。例如,无法连接到服务器或超时等。
import requests
from requests.exceptions import ConnectionError
try:
response = requests.get('https://www.example.com', timeout=0.01)
response.raise_for_status()
except ConnectionError as e:
print("A connection error occurred:", str(e))
4. requests.exceptions.Timeout:当请求超时时,会引发该异常。
import requests
from requests.exceptions import Timeout
try:
response = requests.get('https://www.example.com', timeout=0.01)
response.raise_for_status()
except Timeout as e:
print("The request timed out:", str(e))
5. requests.exceptions.TooManyRedirects:当请求超过最大重定向次数时,会引发该异常。
import requests
from requests.exceptions import TooManyRedirects
try:
response = requests.get('https://www.example.com', allow_redirects=False)
response.raise_for_status()
except TooManyRedirects as e:
print("Too many redirects occurred:", str(e))
以上是requests.exceptions模块常见的一些异常类的使用方法和示例。根据具体的需求,可以根据这些异常类来捕获和处理请求过程中可能发生的错误。
