XPath allows us to query the DOM as if we are working on a XML document. XPath are very fast to locate element in UI and does complex queries to find element in a page. Sometimes we end up having only XPath
as the only option to identify the element comparing to any other locator option such as CSS,ID or Class.
XPath always starts with //
(Double slashes), which means it is going to search for the entire page. If we specify //Input
this means, the XPath is going to query the DOM to search for the first Input type in the page. Another example of returning all the text node in a page we can give //text()
, if we would like to locate an image using XPath, we can either use direct
XPath location or Nth
location. Let’s consider the example
The above image is taken from Wikipedia of bucket sort page, if you need to locate the image using XPath, the direct XPath looks something like this //*[@id=”mw-content-text”]/div/div/a/img
. As you can see here, the image is sitting inside 3rd
DIV where the first DIV id is mw-content-text
. This mechanism of locating image is done via direct XPath.
The XPath is very fragile in nature, means the locating query fails if the DOM structure of the page changes, consider from the above example, what if the image sitting inside 3rd
DIV is moved to second DIV or 4th
DIV, now the query written to select the image fails. Hence the mechanism of Nth
XPath location comes in to play. We can locate the image by writing the XPath as //*[@id=”mw-content-text”]//div/a/img .
What has just happened is we have removed two DIV and used //div,
will directly locate the image regardless of which DIV its sitting, XPath will query to get the first occurance of the image with any DIV it finds the image.
Thus advantage of using direct and Nth location XPath is, the querying of XPath will be fast and efficient.
We can also use attributes in XPath, as mentioned in the previous example we have used id attribute to locate an element using XPath //div[@id=”mw-content-text”]
,here the id name is mw-content-text
, if we need to identify an element using its class we can use @class
We can do partial match while querying using XPath like using Contains() or starts-with() or ends-with().
Consider we have a class
which is dynamically changing (Situation using AJAX) by increment the class name in numbers with a $ sign preceding
to it (e.g. $001_MyClass), then we can using Contains() or ends-with() method. The query looks something like this //div[contains(@class,”MyClass”)] or //div[ends-with(@class,”MyClass”)].
If you are sure only the value after the class names are going to change, then you can safely use starts-with() method (Which you can do it yourself J
Sometimes we may also need to find an element using its text, this can be done like this //div[text()=’Hello’].
You can download a whole list of XPath, CSS, DOM identification table as PDF from here