Tuesday 21 May 2013

Construction of Xpath and Css selectors


Construction of Xpath and CSS selectors


As we know that webdriver supports for different types of locators to identify the web elements(objects i.e username, password etc). 

The different kinds of locators are ,
  • id
  • name
  • xpath
  • css selector
  • class name
  • tag name etc.


The priority of choosing the locator type is id/name, CSS selector and xpath.

Let see how to construct the xpath/css selector for web elements.

Xpath construction:


Let we consider the below login form. In this we will construct the xpath for user name, password text boxes, submit and reset buttons.



The HTML source code for this login page is as follows,


<html>
<title>Welcome to the application!!</title>
<body>
<form name="loginForm">
<table border="1">
<tr>
<td>User Name: </td>
<td>
<input name="username_name" id="username_id" type="text"
class="article-head"/>
</td>
</tr>
<tr>
<td>Password: </td>
<td>
<input name="password_name" id="password_id" type="password"
class="article-head"/>
</td>
</tr>
<tr>
<td>
<input name="login_name" id="login_id" label="Submit" type="button" class="article-head" onClick="submitAction()"/>
</td>
<td>
<input name="reset_name" id="reset_id" label="Reset" type="button" class="article-head" onClick="cancelAction()"/>
</td>
</tr>
</table>
</form>
</body>
</html>

Xpath for user name text field:

Absolute path: html/body/form/table/tr[1]/td[2]/input
Relative path: //input[@id='username_id']
                         //input[@name='username_name']
                         //input[1]

   Also we can use AND OR operators here, as below

                         //input[@id='username_id' and @name='username_name']

Xpath for Submit button:

Absolute path: html/body/form/table/tr[3]/td[1]/input
Relative path: //input[@id='login_id']
                         //input[@name='login_name']
                         //input[3]

   Also we can use AND OR operators here, as below

                         //input[@id='login_id' and @name='login_name']

As same as we can construct the xpath for password text field and reset button.

Xpath for dynamically changing objects:

Let we consider a situation. We want to construct the xpath for the user name text field, which has only two attributs id and type. Also the id is not a constant one, which is dynamic as below,

<input id="username_45833" type="text">

The number in the id name is changing dynamically for every build. In this case using  //input[@id='username_45833'] is not the correct idea.

To accomplish this we have to use the starts-with() function available in the xpath as below

//input[starts-with(@id, 'username_')].

Also we can use ends-with() and contains() method above. For more information about understanding the xpath read here 

4 comments: