關於"<urlopen error [WinError 10054] 遠程主機強迫關閉了一個現有的連接"
首先我是使用python 中 urllib.request 中的 urlopen 這個方法。
話不多說,先來代碼。
我這里為了使用retrying中的retry方法讓這個修飾器的功能為其最大嘗試3次
這里我要說的是一定要在 urlopen() 中不僅僅要把url傳入這個方法中更重要的是在其中設置timeout超時時間,不然你要爬取的網站會默認你是一個攻擊,
導致網站主機強制關閉其鏈接,(他也要保護自己的網站)
from __future__ import (unicode_literals, absolute_import, division, print_function) try: # 如果為python2時 from urllib2.request import urlopen """ 在python2中會有默認的urllib2庫 在python3會有默認的urllib庫 最好還是使用requests模塊吧! """ except ImportError: # 如果為python3時 from urllib.request import urlopen import json import retrying # headers = { # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36", # } ############################## # 一定要設置timeout超時時間原因 # 是會導致對方網站默認為成為攻擊 ############################## @retrying.retry(stop_max_attempt_number=3) def main(url): response = urlopen(url=url, timeout=30) red = response.read() with open("2017_colse_btc.json", 'wb') as f: f.write(red) file_response = json.loads(red) print(file_response) if __name__ == '__main__': json_url = 'https://raw.githubusercontent.com/muxuezi/btc/master/btc_close_2017.json' main(url=json_url)
如果沒有成功在其下面設置close()手動關閉
response = urlopen(url=url, timeout=30) red = response.read() response.close()
這里應該就行了!