如何在通过 Selenium 和 Python 调用 get() 方法时捕获网络故障? [英] How to catch network failures while invoking get() method through Selenium and Python?

查看:47
本文介绍了如何在通过 Selenium 和 Python 调用 get() 方法时捕获网络故障?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Chrome 和 selenium 并且测试运行良好,直到突然互联网/代理连接断开,然后 browser.get(url) 给我这个:

I am using Chrome with selenium and the test run well, until suddenly internet/proxy connection is down, then browser.get(url) get me this:

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

If I reload the page 99% it will load fine, what is the proper way to handle this ?

我的代码:

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')

我不是进入超时异常,而是进入休息部分.

I am not getting into TIMEOUT EXCEPTION but to the break part.

推荐答案

根据您的问题和您的代码试验,当您尝试访问通过参数 传递的 url链接,您可以在以下情况下调整策略:

As per your question and your code trials as you are trying to access the url passed through the argument link you can adapt a strategy where:

  • 您的程序将进行预定义次数的试验以调用所需的 url,您可以通过 range() 传递该网址.
  • 一旦您调用 get(link),您的程序将调用 WebDriverWaiturl 包含一个来自 url 的预定义 partialURL 的预定义间隔.
  • 您可以使用 expected_conditions 方法 title_contains() 并且在 TimeoutException 的情况下再次调用 browser.get(link)catch{} 块内.
  • 您修改后的代码块将是:

  • Your program will make pre-defined number of trials to invoke the desired url, which you can pass through range().
  • Once you invoke get(link) your program will invoke WebDriverWait for a predefined interval for the url to contain a pre-defined partialURL from the url.
  • You can handle this code within a try{} block with expected_conditions method title_contains() and in case of TimeoutException invoke browser.get(link) again within the catch{} block.
  • Your modified code block will be:

#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')

这篇关于如何在通过 Selenium 和 Python 调用 get() 方法时捕获网络故障?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆