python 使用requests模块发送http请求时,ConnectionRefusedError: [WinError 10061] 由于目标计算机积极拒绝,无法连接。

在使用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)

 

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值