即使通过代理连接失败,如何重试当前循环

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了即使通过代理连接失败,如何重试当前循环相关的知识,希望对你有一定的参考价值。

所以我想要废弃一堆链接,但经常发生的是在循环中间(当试图连接到随机链接时),突然通过代理连接失败,循环停止而我的程序结束。

这是代码:

import requests
from bs4 import BeautifulSoup as soup


#Setting Proxy
proxies = {"http": "http://232.454.676.898:8888"}

#List Of Links
link_strings = ['http://foo1.com','http://foo2.com','http://foo3.com', ... ,'http://foo999.com']

for link in link_strings:
    url = link

    uClient = requests.get(url, proxies=proxies)
    page_html = uClient.text
    uClient.close()

    page_soup = soup(page_html, "html.parser")

    #Do some scrapping

那么,如何处理呢? 我应该尝试连接到代理直到成功吗?但是怎么做呢? 或者我应该再次运行当前循环?但是怎么做呢?

答案

尝试捕获requests.get()抛出的异常并循环,直到连接工作:

exception = True
while (exception):
    exception = False
    try:
        uClient = requests.get(url, proxies=proxies)
    except requests.exceptions.RequestException as e:
        exception = True

请注意,如果连接永远不起作用,这可能会创建无限循环!相反,你可以在连接失败时使用continue

try:
    uClient = requests.get(url, proxies=proxies)
except requests.exceptions.RequestException as e:
    continue

以上是关于即使通过代理连接失败,如何重试当前循环的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 python 请求通过另一个代理重试连接?

Win7 easy connect 提示:选路连接失败,可能当前连接网络异常,请稍后重试

Spring Cloud Feign 重试机制-如何实现请求重试

pip 总是无法通过 ssl 验证

Ansible - 在循环中重试失败的迭代

如何利用Spring AOP实现异常重试