Wednesday, April 13, 2016
Indubitably, xpath is one of the most used ways to create locators when automating (often used over Selenium). It's relatively easy to understand and it has enough flexibility for almost every scenario to test.
Of course, there are some times when you have to learn everything when the project is already in progress, so you might have a couple of holes in your knowledge about this. So, for those of you who didn't know about this, I'm gonna explain what are the xpath axes about.
Basically, the axes are keywords that select nodes relative to other nodes. This will be more understandable with an example. So, this is the scenario:
We need to select my name (Jorge Maguiña) from the panel below "Contributors":
But we need to do it in function of the "Contributors" title. This situation can come up when there are repeated ids, or the same element is displayed in several parts of the screen. Selecting an element relatively to another also gives more accuracy to the element. In some cases, it can prevent the locator from becoming obsolete when there's a minor change in the page. So, how do we do it? Keep reading and find out.
Firefox with Firepath (requires Firebug).
So, let's check this:
1. We'll work with a section of this page, so you can open a new tab or work directly here.
2. Right click in any blank space > Inspect in FirePath
3. Click the "Select" (not the actual name) tool at the upper right part of the FirePath panel
4. Click the "Contributors" title. You should see the HTML code for that element:
5. Expand all the nodes at the same level than the selected title:
Typically, we would go down to the nested nodes to reach my name, but in this case we have two ways of getting to the desired element:
a) Going backwards with "../". As in a command line, xpath allows us to go back in the HTML tree with this. For this particular case:
a1. In the "Xpath" text area, enter this: //h2[@class='title']
That means that we are selecting all the h2 nodes that has the class "title".
a2. Now, we add the syntax to go back and select my name: //h2[@class='title']/../div/a/span[contains(text(), 'Jorge Maguiña')]
That means: Select all the h2 nodes that has the class "title", go back one level, select a div, a, span, which contains the text "Jorge Maguiña"
The same can be achieved with axes:
b1. In the "Xpath" text area, enter this: //h2[@class='title']
b2. Add the axis to select the name: //h2[@class='title']/following-sibling::div/a/span[contains(text(), 'Jorge Maguiña')]
The "following-sibling::" part means: select all the following nodes at the same level. The following sibling nodes for "Contributors" are marked in the image below:
So, when you use the xpath, you'll be able to select the name relative to the "Contributors" title:
This is meant to be a basic example, but actually the use of the other axes is very similar. You can see the complete list of axes and their descriptions here.