user3830534
user3830534

Reputation: 15

getting the column cell values of a web table using selenium

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:

    public List<String> getColumnValues(int colIndex) {
        WebElement colElement;
        List<String> colValues = new ArrayList<String>();
        List<WebElement> rows = getRows();
        System.out.println("Rows count: " + rows.size());
        Iterator<WebElement> i = rows.iterator();
        while (i.hasNext()) {
            WebElement row = i.next();
            System.out.println("Row data: " + row.getText());
            // How to avoid this check for the header row for each row
            // iteration?
            if (row.findElements(By.tagName("th")).size() > 0) {
                colElement = row.findElement(By.xpath(".//th[" + colIndex + "]"));
            } else {
                colElement = row.findElement(By.xpath(".//td[" + colIndex + "]"));
            }
            colValues.add(colElement.getText().trim());
        }
        return colValues;
    }

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>

Issue 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 1 Col 2, Row 1 Col 3 etc.

Issue 2. On line 12, the number of elements with tag "th" returned is only 3, whereas there should be 5.

Issue 3. On line 15, I get a no such element exception trying to find .//td[3] even though I can fetch up to //td[5]

Issue 4. As mentioned in the comment, how can I avoid the check for the header row in each iteration of the row element?

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. 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.

Upvotes: 0

Views: 22696

Answers (1)

Deepak
Deepak

Reputation: 336

Use this function. It will return you list containing values in column of which you have provided index as parameter-

public List<String> getColumnValues(int colIndex) {
WebElement colElement;
List<String> colValues = new ArrayList<String>();

colValues = driver.findElements(By.cssSelector("#webtable>tbody>tr>td:nth-child("+colIndex+")"));

return colValues;
    }

Reply if you face any problems.

Upvotes: 1

Related Questions