解决Python使用requests模块发送http请求时出现的ConnectionRefusedError错误

在使用requests进行http请求的时候,遇到了在请求几个页面就报错,在网上结合其他人的解决方法,总结了以下几点。

报错信息:urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='', port=''): Max retries exceeded with url: '' (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001963DDF7D90>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。'))

raise NewConnectionError(
urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x000001963DDF7D90>: Failed to establish a new connection: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

  • 打开设置中自动检测
  • 具体操作参考Python报错:ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。_有无目标计算机积极拒绝,无法连接网络-CSDN博客

  • 在请求前加上
  • proxies = {"http": None, "https": None}
    response = requests.get(url=url, params=params, headers=headers, proxies=proxies, verify=False)
    
  • 加上requests.session() 功能
  • session = requests.Session()
    session.trust_env = False
    response = session.get(url=url, params=params, headers=headers, proxies=proxies, verify=False)
  • 访问频率的设置
  •  在requests发生请求时,由于太过频繁,可以使请求的速度

    time.sleep(1)
    但是加上这个之后还是可能会发生错误提示,sleep会让进程掉线,后来我也将sleep给去掉了
    

    在完成了以上配置之后,正当我以为接下来就是静候佳音了,没想到转眼又给我报另外一个错:ConnectionResetError: [WinError 10054] 远程主机强迫关闭了一个现有的连接。

  • 在request后面加一个关闭的操作或者在headers中把'Connection':'keep-alive'改为'Connection':'close',
  • response = session.get(url=url, params=params, headers=headers, proxies=proxies, verify=False)
    response.close()
    # time.sleep(2)
    
    headers = {
        # 'Connection': 'keep-alive',
        'Connection':'close',
        'User-Agent': '....',
    }
    import requests
    import time
    
    headers = {
        'Connection':'close',
        自行添加
    }
    
    session = requests.Session()
    session.trust_env = False
    for id in range(1, 100):
        params = {
            'id': {id}
        }
    
        proxies = {"http": None, "https": None}
        url = 'http://'      # 需要访问的网站
        response = session.get(url=url, params=params, headers=headers, proxies=proxies, verify=False)
        # response.close()
        # time.sleep(2)
        with open(f'{id}.html', 'w', encoding='utf-8') as f:
            f.write(response.text)

     

    物联沃分享整理
    物联沃-IOTWORD物联网 » 解决Python使用requests模块发送http请求时出现的ConnectionRefusedError错误

    发表评论