Introduction
One of the most common challenges in Selenium automation testing is dealing with web elements that do not appear immediately.
Modern websites frequently use JavaScript, AJAX requests, dynamic content loading and asynchronous operations. When an automation script tries to interact with an element before it becomes available, Selenium may throw exceptions such as NoSuchElementException or ElementNotInteractableException.
Selenium waits help solve this problem by allowing automation scripts to pause execution until a specified condition is satisfied or a maximum waiting time is reached.
There are three commonly discussed wait strategies in Selenium WebDriver:
Implicit Wait
Explicit Wait
Fluent Wait
In this tutorial, we will understand each type with practical Java examples and learn when to use them.
1. What Are Waits in Selenium?
Waits are mechanisms that control how long Selenium waits for elements or conditions during test execution.
For example, consider a login page where the submit button appears only after a JavaScript operation finishes.
Without an appropriate wait, Selenium may try to click the button before it is available.
Waits help make automation scripts more reliable when dealing with dynamic webpages.
2. Implicit Wait in Selenium
Implicit Wait instructs WebDriver to wait for a specified duration when searching for elements that are not immediately available.
Once configured, it applies globally to element-location commands for that WebDriver instance.
Syntax
driver.manage().timeouts()
.implicitlyWait(Duration.ofSeconds(10));Complete Example
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ImplicitWaitExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.manage().timeouts()
.implicitlyWait(Duration.ofSeconds(10));
driver.get("https://example.com");
driver.findElement(By.id("username"))
.sendKeys("testuser");
} finally {
driver.quit();
}
}
}Advantages of Implicit Wait
Easy to configure.
Applies to element searches throughout the session.
Reduces immediate failures when elements take time to appear.
Limitations
It is not designed to wait for specific conditions such as an element becoming clickable.
It applies globally rather than to one particular element.
Combining implicit and explicit waits can produce unpredictable total wait times.
3. Explicit Wait in Selenium
Explicit Wait instructs Selenium to wait until a specific condition becomes true or a timeout occurs.
It is particularly useful for dynamic web applications where different elements may become available at different times.
Selenium provides WebDriverWait and ExpectedConditions to implement explicit waits.
Syntax
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")
)
);Common ExpectedConditions
| Expected Condition | Purpose |
|---|---|
visibilityOfElementLocated() | Waits until an element is visible |
elementToBeClickable() | Waits until an element is visible and enabled |
presenceOfElementLocated() | Waits until an element exists in the DOM |
alertIsPresent() | Waits until a JavaScript alert appears |
titleContains() | Waits until the page title contains specified text |
invisibilityOfElementLocated() | Waits until an element becomes invisible or absent |
textToBePresentInElementLocated() | Waits until specified text appears |
Example: Wait Until an Element Is Clickable
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement loginButton = wait.until(
ExpectedConditions.elementToBeClickable(
By.id("login")
)
);
loginButton.click();Example: Wait Until an Element Is Visible
WebElement username = wait.until(
ExpectedConditions.visibilityOfElementLocated(
By.id("username")
)
);
username.sendKeys("admin");Example: Wait for Text to Appear
wait.until(
ExpectedConditions.textToBePresentInElementLocated(
By.id("message"),
"Login Successful"
)
);Explicit Wait is generally preferred when a test needs to wait for a particular condition rather than simply waiting for an element search.
4. Fluent Wait in Selenium
Fluent Wait is a configurable form of explicit waiting.
It allows testers to define:
Maximum waiting time.
Polling interval.
Exceptions to ignore while waiting.
For example, you can instruct Selenium to check a condition every two seconds for a maximum of twenty seconds.
Syntax
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);Complete Java Example
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
public class FluentWaitExample {
public static void main(String[] args) {
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com");
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(20))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
WebElement element = wait.until(
d -> d.findElement(By.id("username"))
);
element.sendKeys("testuser");
} finally {
driver.quit();
}
}
}The example repeatedly searches for the username field until it is found or the timeout expires.
Advantages of Fluent Wait
Custom polling intervals.
Configurable timeout.
Ability to ignore selected exceptions.
Useful for elements that appear unpredictably.
5. Difference Between Implicit, Explicit and Fluent Wait
| Feature | Implicit Wait | Explicit Wait | Fluent Wait |
|---|---|---|---|
| Scope | Global element searches | Specific condition | Specific condition |
| Configuration | Simple timeout | Timeout and condition | Timeout, polling and ignored exceptions |
| Polling control | No | Limited/default polling configuration | Yes |
| Expected conditions | No | Yes | Can use custom conditions |
| Best suited for | General element searches | Dynamic elements and conditions | Special cases needing custom polling |
Which one should you use?
For most modern Selenium automation projects, explicit waits are a practical default. Fluent Wait is useful when custom polling and exception handling are required. Implicit Wait may be used for simpler element-search scenarios, but avoid combining it with explicit waits in the same test suite.
6. Common Selenium Wait Exceptions
Understanding common exceptions helps automation testers troubleshoot failures.
NoSuchElementException: Selenium cannot find the element using the supplied locator.
TimeoutException: The expected condition was not satisfied within the configured timeout.
StaleElementReferenceException: The element reference is no longer attached to the current DOM, often because the page has changed or refreshed.
ElementNotInteractableException: The element exists but cannot be interacted with in its current state.
In some cases, the correct solution is to wait for the element to become visible, enabled or clickable. For stale elements, it may be necessary to locate the element again after the DOM changes.
7. Best Practices for Selenium Waits
Prefer condition-based explicit waits for dynamic elements.
Avoid using
Thread.sleep()as the default waiting strategy.Do not mix implicit and explicit waits unnecessarily.
Use appropriate ExpectedConditions.
Choose realistic timeout values based on application behaviour.
Re-locate elements when the DOM changes and references become stale.
Use reusable wait methods in automation frameworks.
Avoid waiting for clickability when the actual requirement is only element presence or visibility.
8. Creating a Reusable Explicit Wait Method
In a professional automation framework, wait logic can be placed in a reusable utility class.
public WebElement waitForElement(By locator) {
WebDriverWait wait =
new WebDriverWait(driver, Duration.ofSeconds(10));
return wait.until(
ExpectedConditions.visibilityOfElementLocated(locator)
);
}This method can be reused across multiple test classes and Page Object Model components.
Frequently Asked Questions
1. What are the three types of waits in Selenium?
The commonly used types are Implicit Wait, Explicit Wait and Fluent Wait.
2. Which wait is best in Selenium?
Explicit Wait is generally a good choice because it waits for a specific condition rather than applying a global delay.
3. What is the difference between Explicit Wait and Fluent Wait?
Fluent Wait provides additional control over polling intervals and ignored exceptions. Both are condition-based waiting approaches.
4. Why should Thread.sleep() be avoided?
It pauses execution for a fixed duration regardless of whether the element is already available. This can make tests slower and less efficient.
5. Can implicit and explicit waits be used together?
Although Selenium permits both, combining them can lead to unpredictable waiting times. It is generally better to use explicit waits consistently for condition-based synchronisation.
Learn Selenium Automation Testing with Palium Skills
Palium Skills provides practical automation testing training for freshers, manual testers and working professionals.
The Selenium and Playwright training curriculum can include:
Selenium WebDriver with Java and Python
Implicit, Explicit and Fluent Wait
XPath and CSS Selector
TestNG and PyTest
Page Object Model and automation framework development
API testing and real-time projects
Interview preparation and career guidance
Training modes: Classroom sessions at South Kolkata and Salt Lake centres, plus instructor-led live online training for learners across India.
Contact Palium Skills
Website: www.paliumskills.com
Call: 8420594969 / 7044871915
WhatsApp: 9903130500
Email: info@paliumskills.com
South Kolkata Centre: 1st Floor, Sheeba Bhavan, 1/22 Poddar Nagar (Near South City Mall), Kolkata – 700068.
Salt Lake Centre: 5th Floor, RDB Boulevard, Block GP, Salt Lake Electronic Complex, Kolkata – 700091.
Build your automation testing expertise with practical training from Palium Skills.
No comments:
Post a Comment