Requests报”requests.exceptions.ConnectionError: Failed to establish a new connection: {error message} “的原因以及解决办法

  • Post category:Python

在Python中使用Requests库时,如果出现以下类似的报错信息:

requests.exceptions.ConnectionError: Failed to establish a new connection: 
[Errno 61] Connection refused

或者是:

requests.exceptions.ConnectionError: Failed to establish a new connection: 
[Errno -2] Name or service not known

通常是由于以下原因导致:

  1. 连接的目标服务器无法访问或宕机。
  2. 目标服务器的IP地址或域名填写错误。
  3. 访问目标服务器时,被防火墙阻挡,导致请求不能出去。

我们可以通过以下几种方式来解决这些问题:

  1. 检查目标服务器是否正常运行,确保可以正常访问。
  2. 检查请求的IP地址或域名是否填写正确,并做出相应的修改。
  3. 如果是防火墙问题,解决方法有:

    • 确保目标服务器已经添加到防火墙白名单中。
    • 确认是否需要使用代理服务器。如果需要,可以通过 proxies 参数指定代理服务器。

例如,如果我们遇到了名为 http://example.com 的网站无法访问的问题,我们可以进行以下尝试:

import requests

url = 'http://example.com'
try:
    response = requests.get(url)
    if response.status_code == 200:
        print('Success!')
    else:
        print(f'Response code: {response.status_code}')
except requests.exceptions.ConnectionError as e:
    print('Error:', e)

如果这段代码运行时抛出 requests.exceptions.ConnectionError 异常,则可以尝试以下解决方法:

  1. 检查 example.com 是否正常运行。
  2. 检查请求的URL地址是否填写正确,例如是否缺少了协议部分,或者填写的域名与解析出来的IP地址不匹配。
  3. 如果是防火墙问题,可以检查是否需要添加代理服务器。

进行以上的检查后,就可以解决这个问题了。