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

标签 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());
    }
}

最佳答案

使用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/

相关文章:

java - 让 JPA 生成具有指定行格式的表

java - 如何从java客户端调用MCollective

javascript - 如何从 Protractor 返回对象

python - 在 python 中使用 selenium 循环访问一组 webelement

php - 将 jQuery 与 Selenium WebDriver 结合使用 - 如何将 JSON 对象转换为 WebElement?

python - CEF Python 代理身份验证

java - 如果未找到结果,则显示 Toast

java - Eclipse 中 Spring MVC 模型对象的代码辅助 (jsp/jSTL) View

java - 无法在 Android 上运行 XML 解析器 Jackson

java - 如何将正则表达式与selenium中的url匹配?