selenium_webdriver_introduction
Selenium - WebDriver Introduction
Section titled “Selenium - WebDriver Introduction”Selenium WebDriver is the modern core of the Selenium suite, providing a programming interface to create and run automated tests for web applications. It represents a significant advancement over its predecessor, Selenium RC (Selenium 1), and is often referred to as Selenium 2, 3, or 4 (depending on the version, but the core concept remains WebDriver).
Unlike Selenium RC, which relied on injecting JavaScript into the browser via a proxy server, WebDriver interacts more directly with the browser using the browser’s built-in support for automation or through a browser-specific driver.
Key Features and Advantages
Section titled “Key Features and Advantages”- Direct Browser Communication: Interacts directly with the browser’s automation API, leading to faster and more stable tests.
- W3C Standard: The WebDriver protocol is now a W3C standard, promoting consistency across different browser drivers.
- Object-Oriented API: Provides a more intuitive and cleaner object-oriented API compared to Selenium RC.
- Cross-Browser Support: Supports all major browsers (Chrome, Firefox, Edge, Safari, IE*) through specific driver executables.
- Multi-Language Support: Allows writing tests in various popular programming languages (Java, Python, C#, Ruby, JavaScript, Kotlin).
- Handles Modern Web Features: Better equipped to handle complex elements, dynamic content (AJAX), multiple windows/tabs, alerts, frames, etc.
- No Server Needed (for local execution): Unlike RC, WebDriver doesn’t require a separate server process running for basic local test execution.
- Platform Independent: Tests can run on Windows, macOS, and Linux.
Note: Internet Explorer support requires specific configuration and is generally less stable than modern browsers.
WebDriver Architecture (Simplified)
Section titled “WebDriver Architecture (Simplified)”The interaction typically flows like this:
- Selenium Test Script: Your code (e.g., Java, Python) uses WebDriver API commands.
- JSON Wire Protocol / W3C WebDriver Protocol: Your script sends commands over HTTP to a specific browser driver.
- Browser Driver: A browser-specific executable (e.g.,
chromedriver.exe,geckodriver.exe) acts as a server. It receives the HTTP requests. - Browser: The driver translates the HTTP commands into actions that the browser understands and executes them within the browser.
- Response: The browser sends the result of the action back to the driver, which then sends an HTTP response back to your test script.
This architecture eliminates the need for JavaScript injection and allows for more native interaction with the browser.
WebDriver vs. Selenium RC (Deprecated)
Section titled “WebDriver vs. Selenium RC (Deprecated)”WebDriver is the clear successor and the current standard. Here’s a quick comparison highlighting why:
| Feature | Selenium WebDriver | Selenium RC (Deprecated) |
|---|---|---|
| Architecture | Simpler, direct browser control (via driver). | More complex, requires RC Server as proxy. |
| Communication | Direct driver-browser communication (W3C Protocol). | Script -> RC Server -> Browser (via Selenium Core JS). |
| Speed | Generally faster due to direct interaction. | Slower due to server latency and JS execution. |
| API | More concise, object-oriented. | Less object-oriented, more verbose. |
| Headless Support | Natively supported by most modern browsers/drivers. | Not supported. |
| Mobile Testing | Foundation for mobile testing tools like Appium. | Not designed for mobile. |
| Current Status | Actively developed and supported (W3C Standard). | Deprecated, no longer supported or developed. |
Basic WebDriver Script Example (Java with TestNG)
Section titled “Basic WebDriver Script Example (Java with TestNG)”This example demonstrates the basic structure of a WebDriver test using Java and TestNG. It assumes you have set up a Maven/Gradle project with Selenium and TestNG dependencies, and WebDriverManager (or Selenium Manager) handles driver setup.
package com.example.tests;
import io.github.bonigarcia.wdm.WebDriverManager;import org.openqa.selenium.By;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 WebDriverDemoTest {
private WebDriver driver; private WebDriverWait wait;
@BeforeMethod public void setUp() { // WebDriverManager automatically downloads and sets up the ChromeDriver WebDriverManager.chromedriver().setup(); // Alternatively, Selenium 4.6+ has Selenium Manager built-in // System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver"); // Manual setup (less recommended)
driver = new ChromeDriver(); driver.manage().window().maximize(); // Initialize explicit wait (recommended over implicit wait) wait = new WebDriverWait(driver, Duration.ofSeconds(10)); }
@Test public void calculatePercentTest() { // 1. Navigate to the website driver.get("https://www.calculator.net/");
// 2. Click on Math Calculators link (using explicit wait) WebElement mathCalculatorsLink = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Math Calculators"))); mathCalculatorsLink.click();
// 3. Click on Percent Calculator link WebElement percentCalculatorLink = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Percentage Calculator"))); // Updated Link Text percentCalculatorLink.click();
// 4. Enter value 10 in the first input field WebElement input1 = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("cpar1"))); input1.clear(); input1.sendKeys("10");
// 5. Enter value 50 in the second input field WebElement input2 = driver.findElement(By.id("cpar2")); // Assuming it's immediately available after input1 input2.clear(); input2.sendKeys("50");
// 6. Click Calculate Button // Locator might need adjustment based on actual HTML structure WebElement calculateButton = driver.findElement(By.xpath("//input[@value='Calculate']")); calculateButton.click();
// 7. Get the Result Text and assert // Locator for result might need adjustment WebElement resultElement = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".h2result"))); String resultText = resultElement.getText();
System.out.println("Raw Result Text: " + resultText); // Example assertion: Check if the result text contains 'Result: 5' Assert.assertTrue(resultText.contains("5"), "Calculation result is not correct!"); System.out.println("Calculation test passed!"); }
@AfterMethod public void tearDown() { if (driver != null) { driver.quit(); // Closes all browser windows and ends the WebDriver session } }}This example showcases navigation, element location using different strategies, interaction (click, sendKeys, clear), using explicit waits (WebDriverWait), and basic assertion with TestNG.