我正在尝试从数据表中获取一列。 这是我的表格作为示例,我正在寻找的是从表格中提取名字。
<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());
}
}
最佳答案
使用Java 8
,您可以使用 .forEach
迭代列表仅获取 Firstname
列列表后如下:-
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()));
关于java - Selenium Webdriver - 使用 Java 8 从数据表中获取列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39783013/