XPath is XML query language which can be used for selecting nodes in XML. Hence it can be used to identify elements from DOM since they are represented as XHTML documents. Selenium WebDriver also supports XPath for locating elements. They also help to look for elements in both direction and hence it is generally slow compared to all other locator strategy. We can use XPath with both absolute path and relative path.
Absolute Path refers to specific location in DOM, by considering it’s complete hierarchy. However this is not an ideal locator strategy since it makes your test very brittle. The absolute path will change if there is any change/realignment etc in UI.
Example of Xpath using absolute path is as below
With relative Path , we can find element directly without entire structure. It helps to look out for any elements which matches with specified relative path . Example for a relative path based locator strategy is as below.
Note: Relative XPath starts with “//”
1 2 3 4
Relative XPath - With Attributes
If we need to further narrow down our location strategy, we can use Attributes along with relative XPath. There may be situations where we need to multiple attributes to uniquely identify an element. We can also specify locators to identify for ANY attribute
1 2 3 4 5 6 7
Relative XPath - Partial Match
Sometimes there may be situations where element attributes like ID are dynamically generated. Those will generally have some unique part in attributes likeID and remaining will be generated dynamically , which will keep on changing. This will need a locator strategy which will help us to identify elements using partial match. Main types are
1 2 3 4 5 6 7