Xpath is a language for querying elements from XML-documents. It is used widely used in automated testing as a selector for web-pages elements. It has a pretty simple syntax but provides a good level of agility.
Xpath syntax basics
Xpath operates with node names.
This is an expression to select the node called node3 that is a child of node2, while node2 is a child of node1.
HTML as a type of XML document has a structure of nested nodes. Here’s the basics example of HTML page:
<html> <head></head> </body> <div class="basic-block" id="first-div"> <p>This is the first paragraph.</p> </div> <div class="another-basic-block"> <p>This is the second paragraph.</p> </div> </body> </html>
Let’s use common Xpath commands to select elements of the document from above. We will try to select the <p> tag with help of Xpath expression. Let’s see basic examples.
You can specify the full element’s path from the root:
It will select both paragraph tags from the document. But there’s a much more elegant way to do the same:
Double slash “//” means that you want to select all <p> nodes in ANY place of the document. It helps in a lot of cases, especially when you don’t want to focus on the document structure.
Xpath basic parameters
There’s a way to add more specific conditions into Xpath query. Let’s see it in examples. We need to select a <p> element that is nested into <div> and contains text “first”.
You can specify conditions between square brackets. In the case above we passed there a function contains, that checks if element contains a string in its text.
There’s a common case to select nodes by attribute value. For example:
It will query blocks which has mentioned class name.
You can do the same with id attribute:
Here you can see something new – the * symbol. It means that you want to select ANY element on the page. And square brackets say that the query will chose only nodes with id attribute equal to “first-div” string.
How to check Xpath expressions?
There are useful plugins for popular web-browsers. I want to show you my favorite. It is a plugin for Firefox called FirePath. It is an add-on for a well-known Firefox plugin FireBug (you need to install it first, then install FirePath).
When you finished open FirePath tab inside FireBug panel. You will see an input field. Insert the Xpath query there and plugin will highlight this element(s) on the page. If you expression is not valid, input field will be filled with red color.
You can use Xpath in practice. Check our small Selenium guide, where you can use Java to interact with elements on a web-page programmatically.