原文:http://blog.csdn.net/illegalname/article/details/77164521
今天写爬虫爬取天天基金网站(http://fund.eastmoney.com/)时出现如下图所示的错误。
http://img.my.csdn.net/uploads/201708/14/1502703655_9076.png[WinError 10054] 远程主机强迫关闭了一个现" />
分析原因,是因为使用urlopen方法太过频繁,引起远程主机的怀疑,被网站认定为是攻击行为。导致urlopen()后,request.read()一直卡死在那里。最后抛出10054异常。
具体的解决方法如下:
1. 在request后面写入一个关闭的操作,
2. 设置socket默认的等待时间,在read超时后能自动往下继续跑
-
socket.setdefaulttimeout(t_default)
3.
设置sleep()等待一段时间后继续下面的操作
下面是具体的代码
-
#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) # 自定义
运行结果如下图所示:
http://img.my.csdn.net/uploads/201708/14/1502703750_7609.PNG[WinError 10054] 远程主机强迫关闭了一个现" />
加载中,请稍候......