XPath (XML Path Language) is a query language used to select nodes from XML/HTML documents. It is one of the most powerful and flexible locators in Selenium WebDriver.
Key capabilities:
- ✓Traverse the DOM both upward (to parent) and downward (to children)
- ✓Match elements by attribute, text, position, or relationship
- ✓Use built-in functions:
contains(),starts-with(),text(),position()
Basic Syntax:
XPATH
//tagName[@attribute=''value'']
Types of XPath:
- ✓Absolute XPath — starts from root:
html/body/div/input - ✓Relative XPath — starts from anywhere:
//input[@id=''username'']
Common examples:
XPATH
//input[@id=''username'']
//button[text()=''Login'']
//div[@class=''container'']//a
//*[contains(@id,''user'')]
When to use XPath over CSS: Use XPath when you need to traverse to a parent element — CSS Selector can only go downward.
