Home > Blockchain >  WebDriverWait behave like it doesn't wait
WebDriverWait behave like it doesn't wait

Time:12-28

I'm getting an exception

OpenQA.Selenium.NoSuchElementException: 'no such element: Unable to locate element

Although I'm using WebDriverWait for 10 seconds, it throws exception very fast (almost immidiatly).. like it doesn't wait. At all.

var waitForElement10Sec = new WebDriverWait(driver, TimeSpan.FromSeconds(10));

waitForElement10Sec.Until(ExpectedConditions.ElementIsVisible(By.Id("myForm")));

This is a div which is a wrapper for an input checkbox. All these tags rendered after another button click, then I try to wait before continue. First I tried to wait for the checkbox itself to be clickable but got the same excpetion, so then tried to wait for his parent.

waitForElement10Sec.Until(ExpectedConditions.ElementIsClickable(By.Id("myChkbox"))).Click();

Note - sometimes it success, sometimes it doesn't. I can't point on a cause or different.

I'm using latest nuget package,

  • .NET framework 4.6
  • Chrome v108

CodePudding user response:

Since you did not share all your Selenium code and not a link to the page you are working on we can only guess... So, since simetimes it works and sometimes not there are several possible issues that can cause that:

  1. Your internet connection is too slow or the page you working on is too slow etc. Try increasing the timeout from 10 to 30 seconds.
  2. The element may be on the edge of visible veiwport (screen area detected as visible) - try scrolling that element into the view.

There are more possible issues, but we need to debug your actual code to give better answer

CodePudding user response:

I'm using the following extension method which works for me;

internal static class WebDriverExtensions
{
    public static IWebElement FindElement(this ChromeDriver driver, By by, TimeSpan timeout)
        => FindElement((IWebDriver)driver, by, timeout);

    public static IWebElement FindElement(this IWebDriver driver, By by, TimeSpan timeout, TimeSpan pollingInterval = default)
    {
        // NOTE Also see: https://www.selenium.dev/documentation/webdriver/waits/

        var webDriverWait = new WebDriverWait(driver, timeout)
        {
            // Will default to the DefaultWait polling interval of selenium which is as of writing half a second
            PollingInterval = pollingInterval
        };

        // We're polling the dom, so this is normal procedure and not an exception.
        webDriverWait.IgnoreExceptionTypes(typeof(NoSuchElementException));

        return webDriverWait
            .Until(drv => drv.FindElement(@by));
    }
}

Try that out. The key here is that you ignore the exception and just loop untill the element can be found.

  • Related