Selenium Webdriver - 使用Java 8从数据表中获取列

时间:2016-09-30 03:05:08

标签: java selenium

我正在尝试从数据表中获取一列。 这是我的表用作示例,我正在寻找的是从表中提取名字。

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th>Lastname</th> 
    <th>Age</th>
  </tr>
  <tr>
    <td class="abc">Jill</td>
    <td class="abc">Smith</td> 
    <td class="abc">50</td>
  </tr>
  <tr>
    <td class="abc">Eve</td>
    <td class="abc">Jackson</td> 
    <td class="abc">94</td>
  </tr>
</table>

我如何修改下面的代码给我这个结果:

Jill
Eve 


WebElement table = driver.findElement(By.id("searchResultsGrid"));

// Now get all the TR elements from the table
List<WebElement> allRows = table.findElements(By.tagName("tr"));
// And iterate over them, getting the cells
for (WebElement row : allRows) {
    List<WebElement> cells = row.findElements(By.tagName("td"));
    for (WebElement cell : cells) {
        System.out.println("content >>   " + cell.getText());
    }
}

1 个答案:

答案 0 :(得分:2)

使用Java 8后,您只需获取Firstname列列表,即可使用.forEach对列表进行迭代: -

WebElement table = driver.findElement(By.id("searchResultsGrid"));

List<WebElement> firstCells = table.findElements(By.xpath(".//tr/td[1]"));
firstCells.forEach(firstCell->System.out.println("Firstname >>   " + firstCell.getText()));