Introduction to Selenium WebDriver
Selenium WebDriver is the most widely used browser automation tool in the Selenium suite. It allows testers and developers to automate web applications by simulating user interactions like clicking buttons, filling out forms, and navigating between pages.
Why Use Selenium WebDriver?
β Cross-Browser Testing β Supports Chrome, Firefox, Edge, Safari
β Supports Multiple Programming Languages β Java, Python, C#, JavaScript
β Fast & Efficient β Directly communicates with the browser
β Supports Mobile Testing β Can be used with Appium for mobile automation
β Can Handle Dynamic Web Elements using XPath, CSS Selectors
1. Setting Up Selenium WebDriver
Before writing test scripts, you need to set up Selenium WebDriver on your system.
Step 1: Install Java & IDE
- Install Java JDK (if not already installed)
- Install an IDE like Eclipse or IntelliJ IDEA
Step 2: Download Selenium WebDriver JARs
- Download Selenium JARs from the official website.
- Add them to your Java project.
Step 3: Download Browser Drivers
- Chrome β ChromeDriver
- Firefox β GeckoDriver
- Edge β EdgeDriver
2. Launching a Browser with WebDriver
A simple Selenium script to open a webpage and print the title.
Example: Launch Chrome and Open Google
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class WebDriverBasics {
public static void main(String[] args) {
// Set the path for ChromeDriver
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
// Create WebDriver instance
WebDriver driver = new ChromeDriver();
// Open Google
driver.get("https://www.google.com");
// Print page title
System.out.println("Page Title: " + driver.getTitle());
// Close browser
driver.quit();
}
}
π Explanation:
β System.setProperty()
β Sets the browser driver path
β WebDriver driver = new ChromeDriver();
β Launches Chrome
β driver.get("URL");
β Opens a webpage
β driver.getTitle();
β Retrieves page title
β driver.quit();
β Closes the browser
3. WebDriver Commands
WebDriver provides various commands to interact with the browser.
1οΈβ£ Navigation Commands
driver.navigate().to("https://www.google.com"); // Open a URL
driver.navigate().back(); // Navigate back
driver.navigate().forward(); // Navigate forward
driver.navigate().refresh(); // Refresh page
2οΈβ£ Fetching Page Information
System.out.println(driver.getTitle()); // Get page title
System.out.println(driver.getCurrentUrl()); // Get current URL
System.out.println(driver.getPageSource()); // Get HTML source of the page
3οΈβ£ Closing the Browser
driver.close(); // Closes the current browser window
driver.quit(); // Closes all browser windows and ends the session
4. Locating Web Elements in Selenium
To interact with elements (buttons, input fields, links), Selenium uses locators.
Locator | Syntax | Example |
---|---|---|
ID | By.id("username") |
driver.findElement(By.id("username")); |
Name | By.name("password") |
driver.findElement(By.name("password")); |
Class Name | By.className("login-btn") |
driver.findElement(By.className("btn-primary")); |
Tag Name | By.tagName("input") |
driver.findElement(By.tagName("input")); |
Link Text | By.linkText("Login") |
driver.findElement(By.linkText("Login")); |
Partial Link Text | By.partialLinkText("Log") |
driver.findElement(By.partialLinkText("Log")); |
CSS Selector | By.cssSelector("#login") |
driver.findElement(By.cssSelector("#login")); |
XPath | By.xpath("//input[@name='username']") |
driver.findElement(By.xpath("//input[@name='username']")); |
5. Performing Actions on Web Elements
After locating elements, we can interact with them using Selenium commands.
1οΈβ£ Entering Text in Input Fields
driver.findElement(By.id("username")).sendKeys("testuser");
2οΈβ£ Clicking a Button
driver.findElement(By.id("submit")).click();
3οΈβ£ Getting Text of an Element
String message = driver.findElement(By.id("welcomeMsg")).getText();
System.out.println("Message: " + message);
4οΈβ£ Handling Checkboxes and Radio Buttons
driver.findElement(By.id("rememberMe")).click(); // Click checkbox
boolean isSelected = driver.findElement(By.id("rememberMe")).isSelected(); // Check if selected
6. Handling Browser Alerts and Pop-ups
Handling JavaScript Alerts
driver.switchTo().alert().accept(); // Click OK
driver.switchTo().alert().dismiss(); // Click Cancel
driver.switchTo().alert().sendKeys("Test"); // Enter text
Handling Windows & Tabs
String mainWindow = driver.getWindowHandle();
for (String window : driver.getWindowHandles()) {
driver.switchTo().window(window);
}
// Switch back to main window
driver.switchTo().window(mainWindow);
7. Handling Frames & IFrames
driver.switchTo().frame("frameName"); // Switch to frame
driver.switchTo().defaultContent(); // Exit frame
8. Waits in Selenium WebDriver
1οΈβ£ Implicit Wait (Global Wait)
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
2οΈβ£ Explicit Wait (Specific Element)
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit")));
9. Running WebDriver in Headless Mode
Run Selenium without opening a browser window.
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");
WebDriver driver = new ChromeDriver(options);
10. Best Practices for WebDriver
β
Use Explicit Waits instead of Thread.sleep()
β
Avoid Hardcoded Paths (Use System.getProperty("user.dir")
)
β
Use Page Object Model (POM) for better maintainability
β
Run tests in Parallel using Selenium Grid
β
Handle Dynamic Elements with XPath & CSS Selectors
Conclusion
Selenium WebDriver is a powerful tool for web automation. In this guide, we covered:
β Setting up WebDriver
β Launching Browsers & Navigating Pages
β Locating & Interacting with Elements
β Handling Alerts, Frames, and Windows
β Implementing Waits for Stable Tests