如何在不抛出异常的情况下使用 Selenium 'Until' 函数?

How can I use Selenium 'Until' function without throwing an Exception?

我正在尝试使用 selenium 创建一个测试脚本,它可能会与某个元素交互,但如果该元素不存在,它就不会。我需要补充一点,该元素可能需要一些时间才能出现。问题是,如果我使用 FindElement,则会出现异常。如果我使用 FindElements,则需要很长时间。因此,我尝试使用 "until" 函数,该函数可以很好地等待元素出现……但如果它没有出现,则会引发异常,我想避免这种情况。

我知道我可以试试 catch.But,有没有更好的方法来做到这一点? 我目前有这个:

IWebElement button;
try{
    string x = "search query";
    button = this.WaitDriver.Until(d => d.FindElement(By.XPath(x)));
}catch{
    button = null;
}

如果你想在没有 try-catch 的情况下测试是否存在,那么你将不得不使用 .FindElements()。使用相同的等待时间不应比 .FindElement() 长,但如果元素不存在,等待将超时……这很痛苦。解决此问题的一种方法是执行以下操作。这基本上就是您稍作调整后的结果。

public bool ElementExists(By locator)
{
    try
    {
        new WebDriverWait(driver, TimeSpan.FromSeconds(5)).Until(ExpectedConditions.ElementExists(locator));
        return true;
    }
    catch (Exception e) when (e is NoSuchElementException || e is WebDriverTimeoutException)
    {
        return false;
    }
}

我更喜欢检查是否存在而不是返回 null 因为那样你还必须检查 null。通过将它放在一个函数中,您可以随时调用它并且您的测试保持清洁。你会像

那样使用它
By locator = By.Id("someId");
if (ElementExists(locator))
{
    IWebElement e = driver.FindElement(locator);
    // do something with e
}