1. 程式人生 > >【Python爬蟲錯誤】ConnectionResetError: [WinError 10054] 遠端主機強迫關閉了一個現有的連線

【Python爬蟲錯誤】ConnectionResetError: [WinError 10054] 遠端主機強迫關閉了一個現有的連線

轉載連結:https://blog.csdn.net/illegalname/article/details/77164521

今天寫爬蟲爬取天天基金網站(http://fund.eastmoney.com/)時出現如下圖所示的錯誤。


分析原因,是因為使用urlopen方法太過頻繁,引起遠端主機的懷疑,被網站認定為是攻擊行為。導致urlopen()後,request.read()一直卡死在那裡。最後丟擲10054異常。

具體的解決方法如下:

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)	# 自定義

執行結果如下圖所示:

作者:吾性聖人 
來源:CSDN 
原文:https://blog.csdn.net/illegalname/article/details/77164521?utm_source=copy 
版權宣告:本文為博主原創文章,轉載請附上博文連結!