【Python爬虫错误】ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接
具体的解决方法如下:1. 在request后面写入一个关闭的操作,response.close()2. 设置socket默认的等待时间,在read超时后能自动往下继续跑socket.setdefaulttimeout(t_default)3. 设置sleep()等待一段时间后继续下面的操作time.sleep(t)#coding=utf-8import ...
·
具体的解决方法如下:
1. 在request后面写入一个关闭的操作,
response.close()
2. 设置socket默认的等待时间,在read超时后能自动往下继续跑
socket.setdefaulttimeout(t_default)
3. 设置sleep()等待一段时间后继续下面的操作
time.sleep(t)
#coding=utf-8
import urllib.request
import urllib.error
from bs4 import BeautifulSoup
import time
import socket
socket.setdefaulttimeout(20) # 设置socket层的超时时间为20秒
header = {'User-Agent': 'Mozilla/5.0'}
url = []
print('输入需要查询的基金号,按Q结束\n')
while True:
n = input()
if n == 'Q':
break
elif n:
t = 'http://fund.eastmoney.com/{0}.html?spm-search'.format(n)
url.append(t)
else:
print('输入错误')
for i in url:
request = urllib.request.Request(i, headers=header)
try:
response = urllib.request.urlopen(request)
soup = BeautifulSoup(response, 'html.parser')
title = soup.find('div', attrs={'class': 'fundDetail-tit'})
rate = soup.find('span', attrs={'id': 'gz_gszzl'})
print(title.text, rate.text)
response.close() # 注意关闭response
except urllib.error.URLError as e:
print(e.reason)
time.sleep(1) # 自定义
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)