python中关于<urlopen error [WinError 10054] 远程主机强迫关闭了一个现有的连接

                                     关于"<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()

 这里应该就行了!

猜你喜欢

转载自www.cnblogs.com/luzhi0324/p/12528699.html