Sunday, 28 September 2014

How to Create Relative Xpaths of a Web Page Element ?

To start with the basic coding of WebDriver, one needs to know how to write Xpaths of a web element in a web page.

Xpath of an element is used to access a particular web element in a web page and perform various operations on that web element.

Absolute Xpath starts with root path (/). Thus, its very slow.

Relative Xpath starts with current path (//). Thus, its quite faster than the above one.
//h3/a[text()='Working on New Window']

An easy way to find,

How to Create a Relative Xpath?

1. Open a web Page (lets say in Firefox/Chrome Browser.
2. Press F12 and click on the console.
3. Type: $x("<xpath>") in the console.
4. You will get the result there itself as soon as you hit enter after writing the xpath. And thus, now you are sure that your xpath will never fail in your webdriver code.

Tip :  If you have an ID available then its best way to access the element since its very fast. Else for other you can use many locator strategies out of which here we will talk about creating Relative Xpaths.

Lets , take an example of Facebook website:

The above snapshot depicts 4 kind of Xpaths which we use majorly while accessing the web page elements.
Hence, writing xpaths directly in the console of a web browser helps you in getting the result as the web element and you can directly use that xpath in the code making sure it will never fail.

Explanation of each xpaths in the picture is as follows :

1) Using a class : You can use contains in case there are more than one classes used in a HTML tag. Give a logical class name in contains.

2) Usind ID : If the ID of an element is present in the HTML then no need to write xpath of that element. You can directly use"email") in the code. But in console you can use it to see the output as shown.

3) Using child : If you want to get inside a child node then use "/" to access it. Refer the pic above.

4) Using following-sibling : If you want to access the sibling node of a parent node  then use this as shown in the pic.

There are also various other keywords available to access the web page elements.

One of the Xpath Cheatsheet that I personally found descriptive and useful is : Xpath CheatSheet

Hope this is a useful blog to start with creating relative Xpaths.

Happy Xpathing :)