已解决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)’))
报错代码
粉丝群一个小伙伴用requests.get
爬取网页源码的时候报错(当时他心里瞬间凉了一大截,跑来找我求助,然后顺利帮助他解决了,顺便记录一下希望可以帮助到更多遇到这个bug不会解决的小伙伴),报错代码如下:
def get_url(url):
"""发送请求获取响应返回网页源码"""
# 如果访问失败无限循环访问五次
try:
r = requests.get(url, headers=headers)
except:
time.sleep(120)
for i in range(5):
r = requests.get(url, headers=headers, timeout=20)
if r.status_code == '200':
break
time.sleep(300)
html_str = r.content.decode('utf8')
return html_str
报错信息如下:
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)’))
报错翻译
报错信息翻译:
请求.例外情况。连接超时:http连接池(主机=‘123.96.1.95’,端口=30090):超过url的最大重试次数:http://cdict.qq.pinyin.cn/list?cate_id=461&sort1_id=436&sort2_id=461&page=4(由连接超时报错(<0x00000204934C49A0处的urllib3.连接池.HTTP连接池对象>,‘到123.96.1.95的连接超时(连接超时=20’))引起)
报错原因
若分别指定连接和读取的超时时间,服务器在指定时间没有应答,抛出 requests.exceptions.ConnectTimeout
- timeout=([连接超时时间], [读取超时时间])
- 连接:客户端连接服务器并并发送http请求服务器
- 读取:客户端等待服务器发送第一个字节之前的时间
小伙伴按下面的方法即可解决!!!
解决方法
1. 解决方案,代码设置代理
proxies = {
'http': '127.0.0.1:1212',
'https': '127.0.0.1:1212'
}
r = requests.get(url, headers=headers, proxies=proxies, timeout=20)
2. 调用函数的时候再来一个异常捕获:
try:
get_url(url)
except:
print(url,'爬取失败')
运行之后可以解决
帮忙解决
本文已收录于:《告别Bug》专栏
本专栏用于记录学习和工作中遇到的各种疑难Bug问题,以及粉丝群里小伙伴提出的各种问题,文章形式:报错代码 + 报错翻译 + 报错原因 + 解决方法,包括程序安装、运行程序过程中等等问题,订阅专栏+关注博主后如遇到其他问题可私聊帮忙解决!!!