[WinError 10061] 由于目标计算机积极拒绝,无法连接 解决方案

Python做爬虫时,偶尔抛出异常,然后程序断开,反复检查代码没问题啊?

再重启跑程序,过一段时间又抛异常断开。

翻了好多博客解决方案,都没有起作用。

 网上说有三种情况:

1.Chrome浏览器网络代理问题。

https://blog.csdn.net/xiaoxun2802/article/details/78838857

https://blog.csdn.net/cool_flag/article/details/79174785

2.网速不好,换个网络。

https://blog.csdn.net/qq_32863339/article/details/84302582

3.防火墙问题或者目标主机未开机。

https://blog.csdn.net/theoldsod2000/article/details/8856997

如果你的问题不是这三种情况的话,建议用我的方法试试,或许有效!

其实你会发现程序还是可以正常运行的,只是偶尔抛抛异常,可以用 try / except 处理异常

把经常抛异常的这段代码,写入 try: 中,如果抛异常在 except Exception:  内进行解决。

如何解决?重新调用当前子程序。(但是一定要控制好,可不要出现死递归

def solve(i):

    #防止死递归代码
    if i==5:
        print('error')
        os.system('pause')#暂停
        return -1
    
    #正常运行的代码!
    
    try:
        #偶尔异常代码
    except Exception:
        #重新调用
        time.sleep(5)
        result=solve(i+1)
        if result==-1:
            return -1
    return result
发布了39 篇原创文章 · 获赞 27 · 访问量 4138

猜你喜欢

转载自blog.csdn.net/qq_43381887/article/details/99083072