Answer
Handling Slow-Loading Elements in Selenium
Never use fixed Thread.sleep() for loading — it makes tests slow when things are fast and brittle when things are slow. Use intelligent waits instead.
WebDriverWait + ExpectedConditions (Recommended)
Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
// Wait for element to be visible
WebElement el = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("results"))
);
// Wait for element to be clickable
WebElement btn = wait.until(
ExpectedConditions.elementToBeClickable(By.cssSelector(".submit-btn"))
);
// Wait for text to appear inside element
wait.until(
ExpectedConditions.textToBePresentInElementLocated(By.id("status"), "Success")
);
// Wait for element count
wait.until(
ExpectedConditions.numberOfElementsToBeMoreThan(By.cssSelector(".product-card"), 0)
);
Fluent Wait — Polling with Ignore Exceptions
Java
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofMillis(500))
.ignoring(NoSuchElementException.class)
.ignoring(StaleElementReferenceException.class);
WebElement el = fluentWait.until(
d -> d.findElement(By.cssSelector(".async-loaded"))
);
Implicit Wait (Baseline Only)
Java
// Set once — applies to all findElement calls
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Avoid mixing implicit + explicit waits — they can conflict and cause unexpected timeouts.
Wait for AJAX / API Response
Java
// Wait until loading spinner disappears
wait.until(
ExpectedConditions.invisibilityOfElementLocated(By.cssSelector(".spinner"))
);
// Wait until URL changes (after form submit)
wait.until(ExpectedConditions.urlContains("/dashboard"));
// Wait until page title changes
wait.until(ExpectedConditions.titleContains("Dashboard"));
Common ExpectedConditions
| Condition | Use When |
|---|---|
visibilityOfElementLocated | Element appears on screen |
elementToBeClickable | Button becomes enabled |
invisibilityOfElementLocated | Loader/spinner disappears |
presenceOfElementLocated | Element exists in DOM (may not be visible) |
textToBePresentInElement | Text loads into element |
urlToBe / urlContains | Page navigation completes |
