How to wait until an element is present in Selenium?
Solution 1
You need to call ignoring
with exception to ignore while the WebDriver
will wait.
FluentWait<WebDriver> 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<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30)
.pollingEvery(Duration.ofMillis(200)
.ignoring(NoSuchElementException.class);
Basic tutorial for waiting can be found here.
Solution 2
WebDriverWait wait = new WebDriverWait(driver,5)
wait.until(ExpectedConditions.visibilityOf(element));
you can use this as some time before loading whole page code gets executed and throws and error. time is in second
Solution 3
Let me recommend you using Selenide library. It allows writing much more concise and readable tests. It can wait for presence of elements with much shorter syntax:
$("#elementId").shouldBe(visible);
Here is a sample project for testing Google search: https://github.com/selenide-examples/google
Comments
-
Steve Chambers almost 2 years
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.presenceOfElement(By.id("elementId"));
In case it helps, here is
fluentWait
:FluentWait fluentWait = new FluentWait<>(webDriver) { .withTimeout(30, TimeUnit.SECONDS) .pollingEvery(200, TimeUnit.MILLISECONDS); }
But it throws a
NoSuchElementException
- looks likepresenceOfElement
expects the element to be there so this is flawed. This must be bread and butter to Selenium and don't want to reinvent the wheel... could anyone suggest an alternative, ideally without rolling my ownPredicate
?