WebDriver等待如何等待项目存在或不存在?

Roc*_*e C 5 c# selenium selenium-webdriver

我正在使用Selenium WebDriver运行测试,如果用户没有访问权限,则页面上不存在div.我正在尝试等待,以便如果显示该项目,则返回true,但如果它达到超时,则返回false.

    public bool SummaryDisplayed()
    {
        var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5));
        var myElement = wait.Until(x => x.FindElement(By.Id("summaryPage")));
        return  myElement.Displayed;
    }
Run Code Online (Sandbox Code Playgroud)

我不想使用Thread.Sleep,因为如果2秒后元素存在,我希望它继续.但是如果5秒后元素不存在则返回false.我不希望它抛出异常,在某些测试用例中我预计它不存在.有没有办法可以抑制异常并在超时后返回false?谢谢

Ric*_*ard 8

我认为这对你有用.

public bool SummaryDisplayed()
{
    try
    {
        var wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(5));
        var myElement = wait.Until(x => x.FindElement(By.Id("summaryPage")));
        return  myElement.Displayed;
    }
    catch
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)


Fai*_*aiz 5

您可以使用通用扩展方法等待元素在指定的等待中可见; 然后从您的方法中调用它,如下所示:

public bool SummaryDisplayed()
{
    var summaryElement = driver.WaitGetElement(By.Id("summaryPage"), 5, true);
    return (summaryElement !=null);
} 
Run Code Online (Sandbox Code Playgroud)

扩展方法简单地包装WebDriverWait并等待元素存在/显示,具体取决于您要求的内容.如果在指定的等待中找不到元素,则返回null.我使用此扩展而不是FindElement()在我的框架中.

public static IWebElement WaitGetElement(this IWebDriver driver, By by, int timeoutInSeconds, bool checkIsVisible=false)
{
IWebElement element;
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));

try
{
    if (checkIsVisible)
    {
        element = wait.Until(ExpectedConditions.ElementIsVisible(by));
    }
    else
    {
        element = wait.Until(ExpectedConditions.ElementExists(by));
    }
}
catch (NoSuchElementException) { element = null; }
catch (WebDriverTimeoutException) { element = null; }
catch (TimeoutException) { element = null; }

return element;
}
Run Code Online (Sandbox Code Playgroud)