Custom Explicit Wait

Am looking for a solution to pass IwebElement as the parameter for WebDriverWait in Selenium using c#. I had searched on different forums, blogs to find a solution. Unfortunately, I could not find that. So this is a custom solution with repetition in code :(.

public static IWebElement WaitForElement(IWebDriver driver, By by, int timeOutinSeconds)
{
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOutinSeconds));
return (wait.Until(ExpectedConditions.ElementIsVisible(by)));
}

 

An extension for FindElement in Selenium

The following is a custom extension for FindElement in Selenium using c#. It works perfectly 🙂

public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => drv.FindElement(by));
}
return driver.FindElement(by);
}

public static ReadOnlyCollection<IWebElement> FindElements(this IWebDriver driver, By by, int timeoutInSeconds)
{
if (timeoutInSeconds > 0)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds));
return wait.Until(drv => (drv.FindElements(by).Count > 0) ? drv.FindElements(by) : null);
}
return driver.FindElements(by);
}

 

Usage is pretty straightforward. Simply call this method with required parameters.

WaitForElement(Driver.driver, By.XPath("//a[contains(.,'Room Settings')]"), 20);

driver.FindElement(By.XPath("//input[@class='button primary']"),10);.

 

If you have any doubts please comment below.

Leave a Reply

Your email address will not be published. Required fields are marked *