Selenium - WebDriver
Selenium - WebDriver
Section titled “Selenium - WebDriver”Selenium WebDriver is the core component of the modern Selenium suite. It provides a programming interface (API) to create and run automated tests by directly controlling web browsers. Unlike its predecessor, Selenium RC, WebDriver interacts with the browser using the browser vendor’s native automation support, leading to more stable and faster tests.
Key characteristics of WebDriver:
- Direct Browser Control: Communicates directly with the browser driver (e.g., ChromeDriver, GeckoDriver).
- Language Bindings: Provides APIs for various programming languages (Java, Python, C#, Ruby, JavaScript).
- Cross-Browser Support: Supports automation across major browsers (Chrome, Firefox, Edge, Safari, IE).
- Cross-Platform Support: Runs on Windows, macOS, and Linux.
- Object-Oriented API: Offers a cleaner, more consistent API compared to Selenium RC.
- Handles Modern Web Tech: Better equipped to handle dynamic web pages, AJAX, frames, windows, and alerts.
WebDriver Architecture
Section titled “WebDriver Architecture”The WebDriver architecture is simpler than Selenium RC’s:
- Selenium Client Libraries (Language Bindings): Your test scripts written in Java, Python, etc., using the Selenium API.
- JSON Wire Protocol / W3C WebDriver Protocol: A standardized way for the client libraries to send commands over HTTP.
- Browser Drivers: Executable files provided by browser vendors (e.g.,
chromedriver.exe,geckodriver.exe). These act as servers, listening for commands. - Browsers: The actual browsers (Chrome, Firefox, etc.) receive commands from their respective drivers and execute them.
Your script sends commands (like ‘find element’, ‘click element’) via the protocol to the browser driver. The driver then uses the browser’s built-in automation hooks to execute the command and sends the result back to your script.
WebDriver vs. Selenium RC (Legacy)
Section titled “WebDriver vs. Selenium RC (Legacy)”| Feature | Selenium WebDriver (Modern) | Selenium RC (Deprecated) |
|---|---|---|
| Architecture | Simpler: Script -> Driver -> Browser | Complex: Script -> RC Server -> Browser (via JS injection) |
| Communication | Direct via WebDriver protocol (HTTP) | Indirect via RC Server proxy |
| Speed | Faster | Slower due to extra hop and JS execution |
| API | Object-Oriented, cleaner | Less OO, more procedural |
| Browser Interaction | Uses native browser automation | Relied on JavaScript (Selenium Core) injection |
| Headless Execution | Supported by most modern browsers/drivers | Not directly supported |
| Current Status | Actively Developed & Recommended Standard | Deprecated, Not Supported |
Basic WebDriver Script (Java Example)
Section titled “Basic WebDriver Script (Java Example)”Let’s write a simple script using WebDriver with Java, TestNG, and WebDriverManager (recommended for driver management). We’ll automate searching on Google.
Prerequisites: Java, Maven/Gradle, IDE (Eclipse/IntelliJ).
- Setup Project: Create a Maven project and add Selenium and TestNG dependencies to your
pom.xml:
<dependencies> <!-- Selenium Java --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.10.0</version> <!-- Use latest version --> </dependency>
<!-- TestNG --> <dependency> <groupId>org.testng</groupId> <artifactId>testng</artifactId> <version>7.7.1</version> <!-- Use latest version --> <scope>test</scope> </dependency>
<!-- WebDriverManager --> <dependency> <groupId>io.github.bonigarcia</groupId> <artifactId>webdrivermanager</artifactId> <version>5.3.3</version> <!-- Use latest version --> <scope>test</scope> </dependency></dependencies>- Create Test Class:
package com.example.tests;
import io.github.bonigarcia.wdm.WebDriverManager;import org.openqa.selenium.By;import org.openqa.selenium.Keys;import org.openqa.selenium.WebDriver;import org.openqa.selenium.WebElement;import org.openqa.selenium.chrome.ChromeDriver;import org.openqa.selenium.support.ui.ExpectedConditions;import org.openqa.selenium.support.ui.WebDriverWait;import org.testng.Assert;import org.testng.annotations.AfterMethod;import org.testng.annotations.BeforeMethod;import org.testng.annotations.Test;
import java.time.Duration;
public class GoogleSearchTest {
WebDriver driver; WebDriverWait wait;
@BeforeMethod public void setup() { // WebDriverManager automatically downloads and sets up the ChromeDriver WebDriverManager.chromedriver().setup(); driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); // Explicit wait (10 seconds timeout) driver.manage().window().maximize(); }
@Test public void testGoogleSearch() { // Navigate to Google driver.get("https://www.google.com");
// Find the search box (using name locator) // Wait until the element is present before interacting WebElement searchBox = wait.until(ExpectedConditions.presenceOfElementLocated(By.name("q")));
// Enter search term and press Enter searchBox.sendKeys("Selenium WebDriver"); searchBox.sendKeys(Keys.ENTER);
// Wait for the results page title to contain the search term wait.until(ExpectedConditions.titleContains("Selenium WebDriver"));
// Assert that the title contains the search term Assert.assertTrue(driver.getTitle().contains("Selenium WebDriver"), "Page title does not contain search term.");
// Find and assert that search results stats are displayed WebElement resultStats = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("result-stats"))); Assert.assertTrue(resultStats.isDisplayed(), "Result stats not found.");
System.out.println("Google search test passed!"); }
@AfterMethod public void tearDown() { if (driver != null) { driver.quit(); // Closes all browser windows and ends the WebDriver session } }}- Run Test: Run this class as a TestNG test from your IDE.
Common WebDriver Commands
Section titled “Common WebDriver Commands”Here’s a summary of frequently used WebDriver commands:
| Command | Description |
|---|---|
driver.get("URL") | Navigates to the specified URL. |
driver.findElement(By locator) | Finds the first element matching the locator. |
driver.findElements(By locator) | Finds all elements matching the locator. |
element.click() | Clicks the element. |
element.sendKeys("text") | Types text into the element. |
element.clear() | Clears text from an input element. |
element.getText() | Gets the visible text of the element. |
element.getAttribute("attr") | Gets the value of an element’s attribute. |
element.isDisplayed(), isEnabled(), isSelected() | Checks the state of the element. |
driver.getTitle() | Gets the current page title. |
driver.getCurrentUrl() | Gets the current page URL. |
driver.navigate().back(), forward(), refresh() | Performs browser navigation actions. |
driver.switchTo().frame(index/name/WebElement) | Switches focus to an iframe. |
driver.switchTo().defaultContent() | Switches focus back from a frame to the main page. |
driver.switchTo().window(windowHandle) | Switches focus between browser windows/tabs. |
driver.switchTo().alert().accept(), dismiss(), getText(), sendKeys() | Handles JavaScript alerts, confirms, and prompts. |
driver.manage().window().maximize(), minimize(), setSize() | Controls browser window size and state. |
driver.manage().timeouts().implicitlyWait(Duration) | Sets an implicit wait time (use with caution, prefer explicit waits). |
new WebDriverWait(driver, Duration).until(ExpectedCondition) | Sets an explicit wait for a specific condition. |
driver.quit() | Closes all associated browser windows and ends the session. |
driver.close() | Closes the currently focused browser window. |