Selenium WebDriver C# - 为每个WebElement交互语句处理NoSuchElementException等异常?

时间:2016-02-23 14:42:49

标签: c# selenium-webdriver

是否建议在Selenium WebDriver脚本中为与WebElement交互所涉及的每个语句处理NoSuchElementException等异常?

例如,如果有一个页面有100个元素,我需要通过Selenium WebDriver与它们中的每一个进行交互,那么我是否需要在交互时为每个元素添加try catch块?

1 个答案:

答案 0 :(得分:2)

如果你要求许多try / catch包装器与元素交互,你可能需要考虑一个方便的花花公子包装函数,如下所示:

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元素尝试实现什么样的交互,因此很难根据您的确切目的定制我的答案,但在此示例中,如果{{1}我将使包装函数返回null出现。从那里你可以使用safe navigation operator安全地与可能存在或不存在的元素进行交互。例如:

NoSuchElementException

希望有所帮助!