Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In order to check if an Element is exists and clickble i'm trying to write a boolean method which will wait for the element to be enabled and displyed using C# selenium's webDriverWait as follow:

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

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

In case the above conditions do not happen, I want the method to return 'false'. The problem is that I get exceptions thrown. How can I ignore exceptions such as noSuchElementException and timeOutException in case they are thrown? I have tried to use try catch block but it didn't help and exceptions were thrown.

like image 866
Itay Melamed Avatar asked Mar 29 '17 20:03

Itay Melamed


1 Answers

If you wait for the element to be clickable, it will also be displayed and enabled. You can simply do

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

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

and it will wait for 60s and click the element once it is found. It still may throw an exception if the element is not found, doesn't become clickable, etc. after the timeout expires.

EDIT: Wrapped this up in a function based on OPs comment.

like image 120
JeffC Avatar answered Sep 22 '22 17:09

JeffC