2016-09-30 48 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

相關問題