Hello friends,
I want to retrieve the text of each cell in a column in a web table. I get the column index from a method and pass it as a parameter to this method:
01 public List<String> getColumnValues(int colIndex) {
02 WebElement colElement;
03 List<String> colValues = new ArrayList<String>();
04 List<WebElement> rows = getRows();
05 System.out.println("Rows count: " + rows.size());
06 Iterator<WebElement> i = rows.iterator();
07 while (i.hasNext()) {
08 WebElement row = i.next();
09 System.out.println("Row data: " + row.getText());
10 // How to avoid this check for the header row for each row
11 // iteration?
12 if (row.findElements(By.tagName("th")).size() > 0) {
13 colElement = row.findElement(By.xpath(".//th[" + colIndex + "]"));
14 } else {
15 colElement = row.findElement(By.xpath(".//td[" + colIndex + "]"));
16 }
17 colValues.add(colElement.getText().trim());
18 }
19 return colValues;
20 }
Here is my web table:
<table id = "webtable">
<thead>
<tr>
<th>Header Column 1</th>
<th>Header Column 2</th>
<th>Header Column 3</th>
<th>Header Column 4</th>
<th>Header Column 5</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Col 1</td>
<td>Row 1 Col 2</td>
<td>Row 1 Col 3</td>
<td>Row 1 Col 4</td>
<td>Row 1 Col 5</td>
</tr>
</tbody>
<tbody>
<tr>
<td>Row 2 Col 1</td>
<td>Row 2 Col 2</td>
<td>Row 2 Col 3</td>
<td>Row 2 Col 4</td>
<td>Row 2 Col 5</td>
</tr>
</tbody>
</table>
The issues:
1. On line 5, I get the proper count of the rows. But, on line 9, it is not picking up the row (cell) values. Its printing blanks. I was expecting Row 1 Col 1, Row 2 Col 2 etc.
2. On line 12, the number of elements with tag "th" returned is only 3, whereas there should be 5.
3. On line 15, I get a no such element exception trying to find .//td[3] even though I can fetch upto //td[5]
Can anybody please explain what I might be doing wrong or if there is a better way to get the column values returned as a List<String>. I need the collection with the column values so that I can use it in my Hamcrest Matcher assertion using the hasitem(item) to check whether my table contains a certain value.