Selenium WebDriver C#-是否为每个WebElement交互语句处理类似NoSuchElementException的异常? [英] Selenium WebDriver C# - Handling Exceptions like NoSuchElementException for each and every WebElement interacting statement?

查看:59
本文介绍了Selenium WebDriver C#-是否为每个WebElement交互语句处理类似NoSuchElementException的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否建议为Selenium WebDriver脚本中与WebElement交互所涉及的每条语句处理诸如NoSuchElementException之类的异常?

Is it recommended to handle exceptions like NoSuchElementException for each and every statement which is involved in interacting with WebElement in my Selenium WebDriver script?

例如,如果一个页面包含数百个元素,而我需要通过Selenium WebDriver与每个元素进行交互,那么是否建议我在交互时需要为每个元素添加try catch块?

For example, if there is a page having hundred elements and I need to interact with each of them through Selenium WebDriver, so is it recommended that I need to add try catch block for each of them while interacting?

推荐答案

如果需要与元素进行交互的try/catch包装器,则可能需要考虑一个方便的dandy包装器函数,如下所示:

If you are requiring that many try/catch wrappers for interacting with elements, you may want to consider a handy dandy wrapper function, something like this:

public IWebElement FindElement(By selector)
{
    // Return null by default
    IWebElement elementToReturn = null;

    try
    {
        // Use the selenium driver to find the element
        elementToReturn = Driver.FindElement(selector);
    } catch (NoSuchElementException)
    {
        // Do something if the exception occurs, I am just logging
        Log($"No such element: {selector.toString()} could be found.");
    } catch (Exception e)
    {
        // Throw any error we didn't account for
        throw e;
    }

    // return either the element or null
    return elementToReturn;
}

不能完全确定您试图与这数百种Web元素进行哪种交互,因此很难根据您的确切目的来调整我的答案,但是在此示例中,如果出现NoSuchElementException,我的包装函数将返回null .从那里,您可以使用

Not completely sure what kind of interaction you are trying to achieve with these hundreds of web elements so it's hard to tailor my answer to your exact purpose, but in this example I have the wrapper function returning null if the NoSuchElementException appears. From there you could use the safe navigation operator to safely interact with an element that may or may not exist. For example:

FindElement(By.Id("my-back-button"))?.Click();

Assert.AreEqual("hello", FindElement(By.ClassName("greeting"))?.Text() ?? "");

希望有帮助!

这篇关于Selenium WebDriver C#-是否为每个WebElement交互语句处理类似NoSuchElementException的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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