2016-09-30 78 views
0

我想从数据表中获取一列。 这里是我的表作为例子,我正在寻找的是从表中提取名字。Selenium Webdriver - 从数据表中使用Java获取列8

<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

使用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())); 
+1

我有div ID,我用来到我想要的表,班是不好的做法使用,我从那里拿走它。我开始阅读如何构建自定义xpath,这让我的生活变得更加轻松。感谢您一如既往的输入。 – Moe

相关问题