Back to All Scenarios
Scenario 2 of 100
Locators
Intermediate
Locating Elements with No ID, Name, or Stable XPath
π―Scenario Overview
Locating Elements with No ID, Name, or Stable XPath
Key Takeaways & Cheat Sheet
- βLeverage accessibility attributes (aria-label, placeholder, title)
- βEmploy Selenium 4 Relative Locators (above, below, toLeftOf, toRightOf, near)
- βConstruct robust text-based XPath matching with normalize-space()
- βNavigate relative DOM hierarchy using stable parent containers
Short Direct Answer
When standard attributes like ID or Name are absent, you must look for accessibility elements or positional relationships. Selenium 4 introduces Relative Locators, allowing you to find elements based on their spatial orientation to other stable, known elements. Additionally, you can utilize text-based XPath queries or narrow down search context by first locating a stable container parent.
β οΈ Senior Warning (Red Flag)
If your XPath is highly complex (e.g., with more than 3-4 nested descendant levels), it is a major warning sign. It makes your tests fragile and hard to maintain.
π‘ STAR Deep Dive Explanation & Pro Tip
Relative locators are excellent for forms and grids. Always make sure to combine them with standard explicit waits to guarantee the reference element is visible before locating the target.
SeleniumAutomation.java
Selenium 4 + Javaimport static org.openqa.selenium.support.locators.RelativeLocator.*;
// β
Locate stable reference point
WebElement loginHeader = driver.findElement(By.xpath("//h2[text()='Login']"));
// β
Selenium 4 Relative Locators: Find tag near stable element
WebElement usernameField = driver.findElement(with(By.tagName("input")).below(loginHeader));
// β
Locate relative to stable sibling
WebElement submitButton = driver.findElement(with(By.tagName("button")).below(usernameField));
// β
XPath Text matching with space normalization
WebElement welcomeMsg = driver.findElement(By.xpath("//div[normalize-space()='Welcome back, Guest']"));