【Python爬虫错误】ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接
2023-09-27 14:27:48 时间
具体的解决方法如下:
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) # 自定义
相关文章
- Python精髓之括号家族:方括号、花括号和圆括号,你真的会用吗?
- Python词频统计的3种方法
- Python基础之:Python中的异常和错误
- Python traceback模块的使用(抛异常、报错、输出错误)
- python import logging日志
- Python maximum recursion depth exceeded while calling a Python object (gevent的SSL无限递归错误)的问题解决
- 【华为OD机试真题 python】 城市聚集度【2022 Q4 | 200分】
- 华为python机试题目:计算字符个数、简单错误记录、简单密码、进制转换、句子逆序、密码验证合格程序
- Python 程序员最常犯的十个错误
- Python爬虫技术--基础篇--错误,调试和测试(中)
- Python爬虫技术--基础篇--错误,调试和测试(上)
- python实现线性排序-基数排序
- python中的数字取整(ceil,floor,round)概念和用法
- python ndarray相关操作:拼接
- Python 数据可视化解决方案之 集成 PyPlot 和 PySimpleGUI (教程含源码)
- python django-admin.py startproject xxx 错误:from django.core import management
- 转 Python3 错误和异常/ Python学习之错误调试和测试
- 《Python语言程序设计》——1.8 程序设计错误
- 《从问题到程序:用Python学编程和计算》——2.4 字符串
- Python基础之异常处理+多层异常处理+人为抛出异常指定错误
- python 爬虫 bs4 错误bs4.FeatureNotFound: Couldn‘t find a tree builder with the features you requested
- python:关于postman中生成的基于requests库的接口代码
- Python的lambda表达式、filter、map、reduce等函数的用法
- 用Cython加速Python代码
- python读取文件报gbk错误