XPath in Selenium
What is XPath?
XPath is a query language for selecting nodes from an XML document. In Selenium, we can use XPath to locate a WebElement in the DOM (Document Object Model) to interact and perform any operation on the page.
XPath Syntax
Basic components of a WebElement:
- HTML Tag
- Attributes
XPath Syntax to identify a WebElement in the DOM:
//tagname[@attribute=’Value‘]
Writing effective XPath
While identifying a WebElement using XPath, we have to ensure that it’s unique and reliable enough to increase the test script stability. This can be achieved using a combination of tagname and attribute.
The below practices can help to write an effective XPath:
- Always use relative XPath, it starts with (
//). - Look for unique
idornameattribute. - Look for
classname or combination ofclassnames. - Look for
Sibling,Ancestors, orParentsto identify it uniquely. - Avoid using
textcomparison to locate since any change in the text will break the XPath. - Avoid using any dynamic attribute to locate the XPath.
- Avoid using absolute XPath (
/).