Selenium WebDriver
Dashboard
Topic 5/13
Home โ€บ Testing โ€บ Selenium WebDriver

๐Ÿค– Selenium WebDriver

Selenium 4 architecture, locators, waits (implicit/explicit), and Actions class.

What is Selenium WebDriver?

Selenium WebDriver is an open-source browser automation framework. Selenium 4 communicates natively with browsers via the W3C WebDriver standard protocol.

Locators in Selenium

Locating DOM elements accurately using ID, Name, CSS Selector, XPath, and Relative Locators.

Locator Strategy Java Code Example Best Practice
By.id driver.findElement(By.id("username")) Fastest & most reliable locator.
By.name driver.findElement(By.name("email")) Great for form input fields.
By.cssSelector driver.findElement(By.cssSelector("button.btn-submit")) Fast, versatile, clean syntax.
By.xpath driver.findElement(By.xpath("//button[text()='Submit']")) Supports complex DOM traversal.

Handling Synchronization & Waits

Never use `Thread.sleep()`. Use Implicit and Explicit Waits (`WebDriverWait`) to handle dynamic asynchronous web pages.

SeleniumWaitsTest.java Java
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.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.time.Duration;

public class SeleniumWaitsTest {
  public static void main(String[] args) {
    WebDriver driver = new ChromeDriver();
    driver.manage().window().maximize();

    driver.get("https://app.example.com/login");

    // Explicit Wait
    WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
    WebElement submitBtn = wait.until(
      ExpectedConditions.elementToBeClickable(By.id("submit"))
    );
    submitBtn.click();

    driver.quit();
  }
}

User Actions & Mouse Interactions

Use `Actions` class for drag-and-drop, hover menus, context clicks, and key combinations.

ActionsDemo.java Java
Actions actions = new Actions(driver);
WebElement menu = driver.findElement(By.id("nav-menu"));
WebElement subItem = driver.findElement(By.id("sub-item"));

// Hover and click
actions.moveToElement(menu).click(subItem).perform();