Selenium WebDriver
Synchronization in Selenium
Master synchronization concepts including implicit wait, explicit wait, and fluent wait to handle dynamic web elements effectively.
Understanding Synchronization
What is Synchronization?
Synchronization is a process of matching the speed of application under test and test tool to ensure proper execution flow. During test execution, some elements take longer to become visible while others appear quickly.
Why Do We Need Synchronization?
- • Web pages load at different speeds
- • Elements appear dynamically based on user actions
- • Network latency affects element loading
- • JavaScript execution can delay element availability
Types of Synchronization
1. Unconditional Synchronization (Static Wait)
⚠️ Thread.sleep()
Waits for a fixed amount of time regardless of element availability. Not recommended for production use.
Thread.sleep(5000); // Waits exactly 5 seconds
Disadvantages
- • Always waits for full duration
- • Slows down test execution
- • Not dynamic or intelligent
- • Can cause unnecessary delays
2. Conditional Synchronization (Dynamic Wait)
✅ Dynamic Wait Types
Intelligent waits that check conditions periodically and proceed as soon as the condition is met.
Implicit Wait
Global wait for all elements
Explicit Wait
Local wait with conditions
Fluent Wait
Customizable polling wait
Implicit Wait
Characteristics
- • Also called Global Wait
- • Applies to all findElement() methods
- • Dynamic wait behavior
- • Defined once in Base class
- • Throws NoSuchElementException on timeout
Syntax
driver.manage().timeouts()
.implicitlyWait(Duration.ofSeconds(30));
.implicitlyWait(Duration.ofSeconds(30));
How It Works
1. Set once for entire driver session
2. Applies to every findElement() call
3. Waits up to specified time
4. Proceeds immediately when element found
5. Throws exception if timeout reached
Example Scenario
If set to 30 seconds but element appears in 2 seconds, it will proceed immediately, ignoring remaining 28 seconds.
Complete Example
package Tutorial17;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
public class Demo1 {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/reg");
// Set implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
// All findElement calls will use implicit wait
driver.findElement(By.name("firstname")).sendKeys("Ajay");
driver.findElement(By.name("lastname")).sendKeys("Yadav");
}
}
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
public class Demo1 {
public static void main(String[] args) {
ChromeDriver driver = new ChromeDriver();
driver.get("https://www.facebook.com/reg");
// Set implicit wait
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(30));
// All findElement calls will use implicit wait
driver.findElement(By.name("firstname")).sendKeys("Ajay");
driver.findElement(By.name("lastname")).sendKeys("Yadav");
}
}
Explicit Wait
Characteristics
- • Also called Local Wait
- • Applied to specific elements
- • Requires ExpectedConditions
- • More flexible than Implicit Wait
- • Throws TimeoutException on timeout
Common ExpectedConditions
•
visibilityOf(element)
•
elementToBeClickable()
•
presenceOfElementLocated()
•
alertIsPresent()
•
frameToBeAvailable()
Basic Syntax
WebDriverWait wait = new WebDriverWait(
driver, Duration.ofSeconds(30));
wait.until(ExpectedConditions
.visibilityOf(element)).sendKeys("text");
driver, Duration.ofSeconds(30));
wait.until(ExpectedConditions
.visibilityOf(element)).sendKeys("text");
Advanced Usage
wait.until(ExpectedConditions
.elementToBeClickable(By.id("btn")))
.click();
.elementToBeClickable(By.id("btn")))
.click();
Complete Example
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(15));
// Wait for element to be visible and interact
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("lastname")))
.sendKeys("Yadav");
// Wait for element to be clickable
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='Login']")))
.click();
// Wait for alert and accept
wait.until(ExpectedConditions.alertIsPresent()).accept();
// Wait for element to be visible and interact
wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("lastname")))
.sendKeys("Yadav");
// Wait for element to be clickable
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[text()='Login']")))
.click();
// Wait for alert and accept
wait.until(ExpectedConditions.alertIsPresent()).accept();
Fluent Wait
Advanced Features
- • Customizable polling frequency
- • Exception ignoring capability
- • Most flexible wait mechanism
- • Supports custom conditions
- • Local wait for specific elements
Key Methods
•
withTimeout()
- Maximum wait time•
pollingEvery()
- Check frequency•
ignoring()
- Ignore exceptions•
until()
- Wait conditionBasic Syntax
FluentWait<WebDriver> wait =
new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(Exception.class);
new FluentWait<WebDriver>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(5))
.ignoring(Exception.class);
Custom Function
WebElement element = wait.until(
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("id"));
}
});
new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("id"));
}
});
Polling Timeline Example
Scenario: 30-second timeout with 5-second polling
0s
5s
10s
15s
20s
25s
30s (Timeout)
Checks for element every 5 seconds until found or 30 seconds elapsed
Wait Types Comparison
Feature | Implicit Wait | Explicit Wait | Fluent Wait |
---|---|---|---|
Scope | Global (All elements) | Local (Specific element) | Local (Specific element) |
Conditions | Element presence only | Multiple conditions | Custom conditions |
Polling | Fixed (500ms) | Fixed (500ms) | Customizable |
Exception Handling | NoSuchElementException | TimeoutException | Configurable |
Best Use Case | General element waiting | Specific conditions | Complex scenarios |
Knowledge Check
Knowledge Check
Question 1 of 5
What is the main purpose of synchronization in Selenium?
Key Points Summary
🎯 Best Practices
- • Use Explicit Wait for specific conditions
- • Set reasonable timeout values
- • Avoid Thread.sleep() in production
- • Combine different wait strategies wisely
⚡ Performance Tips
- • Use shorter timeouts for fast elements
- • Implement proper exception handling
- • Choose appropriate polling intervals
- • Monitor wait effectiveness in logs
🔄 When to Use Which Wait
- • Implicit: General element loading
- • Explicit: Specific conditions
- • Fluent: Complex polling needs
- • Thread.sleep: Only for debugging
🚨 Common Pitfalls
- • Mixing implicit and explicit waits
- • Using excessive timeout values
- • Not handling timeout exceptions
- • Overusing static waits