XPath: Ways to define it.

I have recently been working on a project which deals a lot with front-end technologies. While writing automated tests for this project, I came across this interesting thing called the XPath, when trying to locate the various elements in a web application.

I have not dived deep into it yet, but basically, XPath is an XML Path language which helps to locate elements within an XML document.

My current experience with it is mostly through the browser console window, where I get to attempt to select a particular element using the XPath. How I initially started getting the XPaths for the elements I wish to test is that I inspect the element, using the browser tools, copy the XPath and paste it where I need it. If the element has an id, usually, the XPath would be very nice and elegant as shown below. However, in a large project, where element ids are not used a lot, the XPath can be very long.

$x(“//p[@id=’paragraph_body’]”)

Later on, I realised that I did not need the full path in order to locate the element, but a subset of it is sufficient for me to locate the element in the page. Even then, this is still not the most elegant solution as it is very rigid, and any changes to the web page layout might cause the XPath to fail. An example of a simplified XPath is shown below.

$x(“//div/div/div1/span/p”)

In the XPath shown above, the ‘//‘ refers to some element under the hierarchy, and the ‘/‘ refers to a direct child of the element before it.

In order to improve this XPath, I was told that I could use various things such as the class, or any other attributes of the element to locate it more elegantly. For example, a div with class called test-div having a child element containing a paragraph of text which I am locating can be done as shown below.

$x(“//div[@class=’test-div’]//p”)

In this example, the paragraph of text can be one of the children of the div tag or could be a child element of say, a span tag under the div, and the XPath is still able to locate the element I want.

There are also methods such as contains that can be used to check if the attribute contains a particular item or not. For example, if a div has more than one class, contains can be used to still locate the element using a subset of the list of classes. For example,

$x(“//div[contains(@class, ‘test’)]//p”)

which looks for a div tag with a class containing the substring, test, and returns all possible elements that matches it. I have added the p tag to make the example consistent with the previous examples of locating a paragraph text using the XPath.

I hope this short update shares some knowledge on XPaths and how it can be defined and used to locate elements in the web page you are working on.


One thought on “XPath: Ways to define it.

Leave a comment