Selenium WebDriver Guide
Setup, Locators, Waits & Examples
Introduction & Features
Selenium WebDriver is a browser automation framework that allows you to write automated tests for web applications. Control browsers programmatically with real user interactions.
Installation & Setup
Setup Steps
- Add Dependency: Include Selenium WebDriver in your project
- Browser Setup: Install target browsers (Chrome, Firefox, Edge)
- Verify Setup: Run a simple test
Maven Dependencies (pom.xml)
<!-- Selenium WebDriver 4.x - That's all you need! -->
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.27.0</version>
</dependency>
Gradle Dependencies (build.gradle)
dependencies {
implementation 'org.seleniumhq.selenium:selenium-java:4.27.0'
}
Your First WebDriver Test
FirstTest.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class FirstTest {
public static void main(String[] args) {
// Create WebDriver instance - Selenium Manager handles driver automatically!
WebDriver driver = new ChromeDriver();
// Navigate to URL
driver.get("https://www.google.com");
// Get page title
System.out.println(driver.getTitle());
// Close browser
driver.quit();
}
}
Locators & Finding Elements
Locator Types
Locator | Method | Best For
-----------------+-------------------------+---------------------------
ID | By.id() | Most reliable, fastest
Name | By.name() | Form elements
Class Name | By.className() | Single class attribute
Tag Name | By.tagName() | HTML tag elements
Link Text | By.linkText() | Exact anchor text
Partial Link | By.partialLinkText() | Partial anchor text
CSS Selector | By.cssSelector() | Fast, flexible patterns
XPath | By.xpath() | Complex navigation
Locator Examples
// By ID
WebElement element = driver.findElement(By.id("username"));
// By Name
WebElement input = driver.findElement(By.name("email"));
// By CSS Selector
WebElement button = driver.findElement(By.cssSelector(".btn-primary"));
// By XPath
WebElement link = driver.findElement(By.xpath("//a[@href='/login']"));
// Find multiple elements
List<WebElement> links = driver.findElements(By.tagName("a"));
CSS Selector Patterns
// ID selector
#username
// Class selector
.btn-primary
// Attribute selector
input[type='text']
// Descendant selector
div.container button
// Child selector
ul > li
// Multiple classes
.btn.btn-large
Pro Tip
Prefer CSS selectors over XPath for better performance. Use XPath only when CSS cannot achieve the selection (like text-based or parent navigation).
Element Interactions
Interaction Examples
// Click on element
driver.findElement(By.id("submit-btn")).click();
// Type text
driver.findElement(By.name("username")).sendKeys("admin");
// Clear input field
WebElement input = driver.findElement(By.id("search"));
input.clear();
// Get text from element
String text = driver.findElement(By.className("heading")).getText();
// Check if element is visible
boolean isVisible = driver.findElement(By.id("alert")).isDisplayed();
Dropdown Handling
import org.openqa.selenium.support.ui.Select;
WebElement dropdown = driver.findElement(By.id("country"));
Select select = new Select(dropdown);
// Select by visible text
select.selectByVisibleText("India");
// Select by value
select.selectByValue("in");
// Select by index
select.selectByIndex(2);
Waits & Synchronization
Implicit Wait
import java.time.Duration;
// Apply globally for all elements
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
Explicit Wait
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
// Wait for specific condition
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
// Wait for element to be clickable
WebElement element = wait.until(
ExpectedConditions.elementToBeClickable(By.id("submit"))
);
// Wait for visibility
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("message")));
// Wait for presence
wait.until(ExpectedConditions.presenceOfElementLocated(By.className("alert")));
Fluent Wait
import org.openqa.selenium.support.ui.FluentWait;
Wait<WebDriver> fluentWait = new FluentWait<>(driver)
.withTimeout(Duration.ofSeconds(30))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(NoSuchElementException.class);
Quick Examples
Login Automation
driver.get("https://example.com/login");
driver.findElement(By.id("username")).sendKeys("testuser");
driver.findElement(By.id("password")).sendKeys("password123");
driver.findElement(By.id("login-btn")).click();
Form Filling
// Fill text fields
driver.findElement(By.name("firstName")).sendKeys("John");
driver.findElement(By.name("lastName")).sendKeys("Doe");
// Select dropdown
Select country = new Select(driver.findElement(By.id("country")));
country.selectByVisibleText("United States");
// Check checkbox
driver.findElement(By.id("terms")).click();
Window/Tab Handling
// Get current window handle
String mainWindow = driver.getWindowHandle();
// Get all window handles
Set<String> allWindows = driver.getWindowHandles();
// Switch to new window
for (String window : allWindows) {
if (!window.equals(mainWindow)) {
driver.switchTo().window(window);
}
}
// Switch back to main window
driver.switchTo().window(mainWindow);
iframe Handling
// Switch to iframe by index
driver.switchTo().frame(0);
// Switch to iframe by name/id
driver.switchTo().frame("frameName");
// Switch to iframe by WebElement
WebElement frameElement = driver.findElement(By.id("myFrame"));
driver.switchTo().frame(frameElement);
// Switch back to main content
driver.switchTo().defaultContent();
Screenshot Capture
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.OutputType;
import java.io.File;
import org.apache.commons.io.FileUtils;
// Capture screenshot
File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
Next Steps
Continue Your Learning Journey
- Page Object Model (POM) - Design pattern for maintainable test automation
- TestNG Integration - Framework annotations, assertions & test configuration
- Data-Driven Testing - Parameterize tests with Excel, CSV or database
- Selenium Grid - Parallel execution across multiple browsers
- Reporting - Generate rich reports with Extent Reports or Allure
- CI/CD Integration - Automate test execution with Jenkins or GitHub Actions