Locator Strategies

Selenium supports many strategies for finding elements. Prefer IDs and data-testids; fall back to CSS selectors. Avoid brittle XPath when possible.

All locator types

java
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

// By ID (fastest)
WebElement el = driver.findElement(By.id("submit-btn"));

// By Name
el = driver.findElement(By.name("username"));

// By CSS Selector
el = driver.findElement(By.cssSelector(".login-form > button[type='submit']"));

// By XPath
el = driver.findElement(By.xpath("//button[text()='Login']"));

// By Class (use CSS instead when possible)
el = driver.findElement(By.className("nav-link"));

// By Link Text
el = driver.findElement(By.linkText("Forgot password?"));

// By Partial Link Text
el = driver.findElement(By.partialLinkText("Forgot"));

// Find multiple elements
List<WebElement> rows = driver.findElements(By.cssSelector("table tbody tr"));

Relative Locators (Selenium 4+)

java
import static org.openqa.selenium.support.locators.RelativeLocator.with;

WebElement passwordField = driver.findElement(
    with(By.tagName("input")).below(By.id("username"))
);