Selenium + Java · Lesson 17 of 44

0/44 done

Module 17: Locators

17. Professional Locators: Robust XPath, CSS & Axes Strategies

18 minlesson

Your task

Implement createDynamicButtonXPath:

  1. Accept String buttonText.
  2. Return By.xpath("//button[contains(normalize-space(), '" + buttonText + "')]").

Write it in the editor, then press Check answer (Ctrl + Enter).

Locator Hierarchy (Reliability Order)

  1. By.id("login-btn") - Fastest & unique
  2. By.cssSelector("button[data-testid='submit']") - Fast & readable
  3. By.xpath("//button[contains(text(), 'Submit')]") - Powerful text search
  4. By.xpath("//td[text()='ORD-101']/following-sibling::td//button") - XPath axes
java
// XPath Axes:
// Find delete button for a specific table user:
By deleteBtn = By.xpath("//tr[td[contains(text(), 'Dhanu')]]//button[@aria-label='Delete']");

Key Takeaways & Walkthrough Summary

In Selenium, flaky locators are the number one cause of test failures. In this lesson, we master By.id, By.cssSelector, and relative XPath with contains, starts-with, and XPath axes like following-sibling and ancestor. Let's build resilient locators!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why should absolute XPath (/html/body/div[1]/...) be forbidden?

Any minor DOM change or newly added header container immediately breaks absolute paths. Always use relative XPath with attributes or text.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip