首页 > 解决方案 > 如何在通过 Selenium 和 Python 调用 get() 方法时捕获网络故障?

问题描述

我正在使用带有 selenium 的 Chrome,并且测试运行良好,直到突然互联网/代理连接断开,然后 browser.get(url) 得到我这个: 在此处输入图像描述

如果我重新加载页面 99% 它将加载正常,处理此问题的正确方法是什么?

我的代码:

def web_adress_navigator(browser, link):
"""Checks and compares current URL of web page and the URL to be navigated and if it is different, it does navigate"""

try:
    current_url = browser.current_url
except WebDriverException:
    try:
        current_url = browser.execute_script("return window.location.href")
    except WebDriverException:
        current_url = None

if current_url is None or current_url != link:
    retries = 5
    while retries > 0:
        try:
            browser.get(link)
            break
        except TimeoutException:
            logger.warning('TimeoutException when tring to reach page')
            retries -= 1
            while not is_connected():
                sleep(60)
                logger.warning('there is no valid connection')

我没有进入 TIMEOUT EXCEPTION 而是进入休息部分。

标签: pythonseleniumselenium-webdriverproxywebdriver

解决方案


根据您的问题和代码试验,当您尝试访问通过参数传递的urllink时,您可以采用以下策略:

  • 您的程序将进行预定义的试验次数来调用您可以通过的所需urlrange()
  • 一旦你调用get(link)你的程序将调用WebDriverWait为一个预定义的时间间隔url 包含一个预定义partialURLurl
  • 您可以使用expected_conditions方法title_contains()try{}在块内处理此代码,以防在块内再次调用。TimeoutExceptionbrowser.get(link)catch{}
  • 您修改后的代码块将是:

    #imports
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.common.exceptions import TimeoutException
    # other code works
    browser.get(link)
    for i in range(3):
        try:
            WebDriverWait(browser, 10).until(EC.title_contains(partialTitle))
            break
        except TimeoutException:
            browser.get(link)
    logger.warning('there is no valid connection')
    

推荐阅读