繁体   English   中英

使用c#selenium webdriverWait wait.untill()函数时忽略异常

[英]Ignoring exceptions when using c# selenium webdriverWait wait.untill() function

为了检查Element是否存在并且clickble我正在尝试编写一个布尔方法,该方法将使用C#selenium的webDriverWait等待元素启用和显示,如下所示:

webDriverWait wait = new webDriverWait(driver,timeSpan.fromSeconds(60));

Wait.untill(d => webElement.enabled()&& webElement.displayed());

如果上述条件没有发生,我希望该方法返回'false'。 问题是我抛出了异常。 如果抛出它们,我怎么能忽略noSuchElementException和timeOutException之类的异常? 我试图使用try catch块,但它没有帮助,抛出了异常。

WebDriverWait实现包含public void IgnoreExceptionTypes(params Type [] exceptionTypes)方法的DefaultWait类。

您可以使用此方法定义在单击之前等待元素启用时要忽略的所有异常类型。

例如 :

WebDriverWait wdw = new WebDriverWait(driver, TimeSpan.FromSeconds(120));
wdw.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException));

在前面的代码中,wait将忽略NoSuchElementException和ElementNotVisibleException异常

如果您等待元素可点击,它也将显示并启用。 你可以干脆做

public bool IsElementClickable(By locator, int timeOut)
{
    try
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementToBeClickable(locator));

        return true;
    }
    catch (WebDriverTimeoutException)
    {
        return false;
    }
}

它将等待60秒并在找到元素后单击该元素。 如果在超时到期后未找到元素,不会变为可点击等,它仍然可能抛出异常。

编辑:在基于OPs评论的功能中包装它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM