Selenium Chromedriver not waiting and throwing ElementNotFound when using WebDriverWait until findelement

    async Task RunWorker(ConcurrentQueue<string> idList)
    {
        var driver = new ChromeDriver();
        while (idList.TryDequeue( out var nextId ))
        {
            var url = GetNextUrl( nextId );
            driver.Navigate().GoToUrl( url );
            var waiter = new WebDriverWait( driver, TimeSpan.FromSeconds(10)  );                  
            waiter.Until( driver => driver.FindElement( By.XPath( "//div[@id='DocumentdetailsDiv']" ) ) );
        }
        driver.Quit();    
    }

waiter.Until throws an ElementNotFound exception immediately without explicitly waiting 10 seconds. Curiously, if i debug the program, and wait 1 second until I run the Until, then it waits as expected. Not sure what I am doing wrong, as all the sample code I see uses this same methodology.

1 answer

  • answered 2020-10-29 23:14 VoidA313

    Selenium WEB Driver has two wait types

    1. Implicit Wait
    2. Explicit Wait

    In your case you have use "Implicit Wait" and used "FindElement" method which is not supported by Implicit wait timeout condition.

    Please use "Explicit Wait" with "Fluent Wait" Syntax:

    Wait wait = new FluentWait(WebDriver reference)
    

    .withTimeout(timeout, SECONDS) .pollingEvery(timeout, SECONDS) .ignoring(Exception.class);

    Your code would look like below once we applied Explicit FluentWait

    async Task RunWorker(ConcurrentQueue<string> idList)
    {
        var driver = new ChromeDriver();
        while (idList.TryDequeue( out var nextId ))
        {
            var url = GetNextUrl( nextId );
            driver.Navigate().GoToUrl( url );
            Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)                            
            .withTimeout(30, TimeUnit.SECONDS)          
            .pollingEvery(5, TimeUnit.SECONDS)          
            .ignoring(NoSuchElementException.class);
    
            WebElement clickseleniumlink = wait.until(new Function<WebDriver, WebElement>(){
    
            public WebElement apply(WebDriver driver ) {
                return driver.findElement(By.xpath("//div[@id='DocumentdetailsDiv']"));
               }
           });
    
        //click on the selenium link
        clickseleniumlink.click();
        }
        driver.Quit();    
    }
    

    Please update above code to match with your object names, I only applied the sequence.

    You can find further details here, ref: https://www.guru99.com/implicit-explicit-waits-selenium.html