已解决:requests.exceptions.ConnectTimeout错误解析与解决方案
在使用Python的requests库进行网络请求时,有时会遇到连接超时的问题。报错信息如下:
requests.exceptions.ConnectTimeout: HTTPConnectionPool(host=‘123.96.1.95’, port=30090): Max retries exceeded with url: http://cdict.qq.pinyin.cn/list?cate_id=461&sort1_id=436&sort2_id=461&page=4 (Caused by ConnectTimeoutError(<urllib3.connection.HTTPConnection object at 0x00000204934C49A0>, ‘Connection to 123.96.1.95 timed out. (connect timeout=20)’))
这个错误通常发生在尝试连接到某个服务器时,但是在设定的超时时间内没有建立连接。在这个具体的例子中,代码试图连接到IP地址为123.96.1.95,端口号为30090的服务器,但在20秒内未能成功建立连接。
以下是一个可能导致上述错误的代码示例:
import requests
url = "http://cdict.qq.pinyin.cn/list?cate_id=461&sort1_id=436&sort2_id=461&page=4"
try:
response = requests.get(url, timeout=20) # 设置超时时间为20秒
response.raise_for_status() # 如果响应状态码不是200,就主动抛出异常
except requests.exceptions.RequestException as e:
print(e)
在这段代码中,如果服务器在20秒内没有响应,就会触发ConnectTimeout异常。
为了解决这个问题,可以采取以下措施:
以下是修改后的代码示例:
import requests
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
url = "http://cdict.qq.pinyin.cn/list?cate_id=461&sort1_id=436&sort2_id=461&page=4"
# 创建一个Session对象
session = requests.Session()
# 设置重试策略
retries = Retry(total=3, backoff_factor=0.1, status_forcelist=[500, 502, 503, 504])
session.mount('http://', HTTPAdapter(max_retries=retries))
try:
response = session.get(url, timeout=30) # 增加超时时间到30秒
response.raise_for_status()
except requests.exceptions.RequestException as e:
print(e)
在这个修正后的代码中,我们使用了requests.Session和Retry来自动处理请求的重试,并且增加了超时时间到30秒。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有