Xpath essentials

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 logo

Xpath syntax basics

Xpath operates with node names.

/node1/node2/node3

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:

/html/body/div/p

It will select both paragraph tags from the document. But there’s a much more elegant way to do the same:

//p

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”.

//div/p[contains(.,'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:

//div[@class='text-block']

It will query blocks which has mentioned class name.

You can do the same with id attribute:

//*[@id="first-div"]

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.

xpath basics firepath

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.

Leave a Reply

Be the First to Comment!