How to wait until an element is present in Selenium?

后端 未结 5 1607
情话喂你
情话喂你 2020-11-27 02:53

I\'m trying to make Selenium wait for an element that is dynamically added to the DOM after page load. Tried this:

fluentWait.until(ExpectedConditions.presen         


        
5条回答
  •  清歌不尽
    2020-11-27 03:54

    You need to call ignoring with exception to ignore while the WebDriver will wait.

    FluentWait fluentWait = new FluentWait<>(driver)
            .withTimeout(30, TimeUnit.SECONDS)
            .pollingEvery(200, TimeUnit.MILLISECONDS)
            .ignoring(NoSuchElementException.class);
    

    See the documentation of FluentWait for more info. But beware that this condition is already implemented in ExpectedConditions so you should use

    WebElement element = (new WebDriverWait(driver, 10))
       .until(ExpectedConditions.elementToBeClickable(By.id("someid")));
    

    *Update for newer versions of Selenium:

    withTimeout(long, TimeUnit) has become withTimeout(Duration)
    pollingEvery(long, TimeUnit) has become pollingEvery(Duration)
    

    So the code will look as such:

    FluentWait fluentWait = new FluentWait<>(driver)
            .withTimeout(Duration.ofSeconds(30)
            .pollingEvery(Duration.ofMillis(200)
            .ignoring(NoSuchElementException.class);
    

    Basic tutorial for waiting can be found here.

提交回复
热议问题