Saturday 22 October 2016

Access Web Elements inside Table with Selenium



Accessing Web Elements Inside a table using xpath is very important to learn as you will need it to write automated Selenium Test Cases.As it is very difficult for developers to provide ids for each table element hence we need to use Xpath for accessing each cell element. So this post is very useful to understand accessing table using Selenium.

Accessing Table Cell Element -

HTML Code -
 

<html>
<body>
<table id="table1">
<table>
<tr>
<td>first </td>
<td>second </td>
</tr>
<tr>
<td>third</td>
<td>four </td>
</tr>
<table>
</body>
</htmt>

Xpath Writing - Let us write xpath for clicking on cell with text "thrid"

As we know XPath locators  start with a double forward slash "//" and then followed by the parent tag name. Since we are dealing with tables, the parent element will be the <table> tag. The first part of our XPath will be "//table".

The element with tab <tbody> is under <table> means <tbody> is child tag of  of <table>. Now oue xpath will be modified as "//table/tbody".

Now inside <tbody> we need to access the second <tr> and first <td> so now xpath will be modofied as "//table/tbody.tr[2]/td[1]".

WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));  

Accessing Nested Table Cell Element -

HTML Code -


<html>
<body>
<!-- Outer Table -->
<table id="table1">
<tbody>
<tr>
<td>first </td>
<td>second </td>
</tr>
<tr>
<td>third</td>
<!-- Inner Table -->
<table id="table2">
<tbody>
<tr>
<td>first 1</td>
<td>second 2</td>
</tr>
<tr>
<td>third 3</td>
<td>four 4 </td>
</tr>
</tbody>
<table>
</tr>
</tbody>
<table>
</body>
</htmt>

Xpath Writing -

Xpath for locating "second 2"


WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]
                                                 +"/table/tbody/tr[1]/td[2]"));

Accessing table elment using attributes -

When the there are multiple tables in HTML code or if the tables are too much nested we can use any of the attributes provided in html code such as Id, Width, height, values etc. Refer the first html code where table id is given as table 1 then we can write xpath as per shown below 


WebElement thirdCell = driver.findElement(By.Xpath("//table[@id=\"table1\"]/tbody/tr[2]/td[1]"));  


7 comments:

  1. I have to thank for sharing this blog admin, really helpful to me.

    Technology
    ejobsalert

    ReplyDelete