XPATH: locating elements with xpath

Last updated on:

Most of the time I didn't pay attention to the way you can locating elements on the page, specially when you have Firefox extensions such as WebDriver Element Locator, but at some certain point you realizing that it is quite unreliable and in case of native mobile applications it will not work, so what is right way to use xpath?

If google for xpath tutorials you most likely you will faced to http://www.w3schools.com/xpath/ and to be honest it one of the resources I have started using for better understanding xpath and Useful XPATH patterns from seleniumhq.

First all let see where we placing xpath using WebDriver:

driver.findElement(By.xpath("yariyara");

Let say user on google web page he wants locate container which containing form and in that form I want find second container:

.//div/form/div[2]

And then he decided to find element with specific id

.//div/form/div[@id='yariyarayara']

And then at some point he decided to select last input field in that specific form:

.//div/form/input[last()]

Actually wait a second, not the last one, but the one above it:

.//div/form/input[last() -1]

But why select only one field, if he can select more? So he decided to select first two input fields:

.//div/form/input[position()<1]

What we want select class attribute with specific value:

.//span[@class='price']

And if we need select all child nodes under specific class:

.//span[@class='price']/*

If we need select all div elements which have any attribute:

.//div[@class='pslmain']/div/@*

And in case we need select nodes of specific div element we would use:

.//div[@class='pslmain']/div/node()

Selects two non related elements, for example all elements of the first container AND 3rd container in the document:

.//div[@class='pslmain'] | .//div[3]/*

Or let say we want selects all element children of the current node:

.//div[@class='pslmain']/child::*

Or do the same thing with attribute:

.//div[@class='pslmain']/attribute::*

You might also find useful to look for attribute which contains specific text:

//div[contains(text(), '38,16')]

Or let say you just want see if the class name having specific characters:

//input[starts-with(@class, 'srl_')]
View Comments

Leave a Comment

Use markdown or basic HTML and be nice.