πŸ’‘ If you like this website, please share it with your friends and network! πŸš€
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 + Java
import 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']"));