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

Python中requests.exceptions.ConnectionError异常的处理方法

发布时间:2024-01-11 18:07:50

在Python中,requests是一个常用的发送HTTP请求的库。requests库中的异常模块requests.exceptions定义了一系列可能出现的异常情况,其中之一就是ConnectionError异常。

ConnectionError异常表示请求过程中发生了连接错误,可能是网络连接问题、域名解析错误等。为了能够有效地处理这个异常,可以使用try/except语句来捕获并处理ConnectionError异常。

以下是一个使用requests库发送HTTP请求,并处理ConnectionError异常的示例代码:

import requests
from requests.exceptions import ConnectionError

def send_request(url):
    try:
        response = requests.get(url)
        response.raise_for_status() # 如果请求返回的状态码不是200,会抛出一个HTTPError异常
        return response.text
    except ConnectionError:
        print("ConnectionError: Unable to establish connection to the server.")
    except requests.exceptions.HTTPError as http_error:
        print(f"HTTPError: {http_error}")
    except requests.exceptions.RequestException as request_exception:
        print(f"RequestException: {request_exception}")

# 测试发送请求
url = "http://example.com"
response = send_request(url)
if response:
    print(response)

在上述代码中,send_request函数接受一个url作为参数,使用requests库发送GET请求。在try代码块中,首先发送请求并获取响应。然后使用response.raise_for_status()方法来检查响应的状态码,如果状态码不是200,会抛出一个HTTPError异常。

如果发送请求过程中发生了ConnectionError异常,except代码块中的代码会被执行,并输出错误信息"ConnectionError: Unable to establish connection to the server."。

如果发送请求后,服务器返回的状态码不是200,会抛出一个HTTPError异常,except代码块中的代码会被执行,并输出错误信息"HTTPError: <错误信息>"。

如果发送请求过程中出现了其他异常,requests库会抛出一个RequestException异常,except代码块中的代码也会被执行,并输出错误信息"RequestException: <错误信息>"。

通过这样的错误处理机制,可以在请求过程中捕获并处理ConnectionError异常,提高程序的健壮性。