Problem
In the past HTML tables were used to structure (lay-out) the entire page. There are many disadvantages by using tables, like they use more bytes of markup, they prevent incremental rendering, tables break text while copying, implementing table based layout takes more time, and so on… Fortunately, the switch was made to use div containers to structure the layout and tables to represent data, like in Microsoft Excel.
Tables are defined in HTML with the <table> tag. A table consist of columns and rows. Columns are defined with the <td> tag and row are defined with the <tr> tag. In this example we will locate some cells of the following table.
<table id="simpleTable" border="1">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
1
2
3
4
5
6
7
8
9
10
11
12
|
<table id="simpleTable" border="1">
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
|
Solution
We will see how we can locate each table cell.
Locate table cell 1: css=table#simpleTable tbody tr:nth(1) td:nth(1)
Locate table cell 2: css=table#simpleTable tbody tr:nth(1) td:nth(2)
Locate table cell 3: css=table#simpleTable tbody tr:nth(2) td:nth(1)
Locate table cell 4: css=table#simpleTable tbody tr:nth(2) td:nth(2)
What has been done
The table structure is useful to walk through the table to locate the required table cell. (like XPath does for XML)
There is more
Sometimes developers are making the distinction between the header, footer and body. If so, you will see:
<table id="complexTable" border="1">
<thead>
<tr>
<th>Testcase</th>
<th>Pass/Fail</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td>1 passed / 1 failed</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Testcase 1</td>
<td>Failes</td>
</tr>
<tr>
<td>Testcase 2</td>
<td>Passed</td>
</tr>
</tbody>
</table>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<table id="complexTable" border="1">
<thead>
<tr>
<th>Testcase</th>
<th>Pass/Fail</th>
</tr>
</thead>
<tfoot>
<tr>
<td></td>
<td>1 passed / 1 failed</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Testcase 1</td>
<td>Failes</td>
</tr>
<tr>
<td>Testcase 2</td>
<td>Passed</td>
</tr>
</tbody>
</table>
|
Locate body table cells We will locate the value in the third row from the first column. css=table#complexTable tbody tr:nth-child(2) td
We will locate the value in the second row from the second column. css=table#complexTable tbody tr td:nth-child(2)
Locate header table cells We will locate the column name of the second column. css=table#complexTable thead tr th:nth(2)
Locate footer table cells We will locate the footer value in the second column. css=table#complexTable tfoot tr td:nth(2)