2016-02-29 70 views
0

在我的腳本(selenium & Java)中,我需要通過標題選擇一個表列。 基本上,我將頭部作爲參數發送,然後通過該列進行讀取。selenium - 按標題選擇一列

但問題是,我無法獲得標題列的索引。 任何想法或建議?

<table class="table table-hover tablesorter ib-table" data-reactid=".0.0.0.1.2.0"> 
<thead data-reactid=".0.0.0.1.2.0.0"> 
<tr data-reactid=".0.0.0.1.2.0.0.0"> 
<th data-reactid=".0.0.0.1.2.0.0.0.0">ID</th> 
<th data-reactid=".0.0.0.1.2.0.0.0.1">To</th> 
<th data-reactid=".0.0.0.1.2.0.0.0.2">From</th> 
<th data-reactid=".0.0.0.1.2.0.0.0.3">Text</th> 
</tr> 
</thead> 
<tbody data-reactid=".0.0.0.1.2.0.1" style="height: auto;"> 
<tr data-reactid=".0.0.0.1.2.0.1.$0"> 
<td data-reactid=".0.0.0.1.2.0.1.$0.0">123456</td> 
<td data-reactid=".0.0.0.1.2.0.1.$0.1">+0156477889785</td> 
<td data-reactid=".0.0.0.1.2.0.1.$0.2">+0156477889784</td> 
<td data-reactid=".0.0.0.1.2.0.1.$0.3">sample textM</td> 
</tr> 
<tr data-reactid=".0.0.0.1.2.0.1.$1"> 
<tr data-reactid=".0.0.0.1.2.0.1.$2"> 
+1

這將是更容易幫助你,如果你提供'你已經嘗試已經 – Andersson

回答

0

首先,你需要通過

List<WebElement> headersList = driver.findElement(By.xpath("//table[@class='table-hover tablesorter ib-table']")).findElements(By.tagName("th")); 

後你打算把所有的TR中環做了所有的頭一個列表

List<WebElement> trList = driver.findElement(By.xpath("//table[@class='table-hover tablesorter ib-table']")).findElements(By.tagName("tr")); 

List<WebElement> tdList; 

for(int = i ; i < trList.Count ; i++) 
{ 
tdList = trList[i].findElements(By.tagName("td")); 

//tdList[0] its header in index[0]... and so on... 
} 
+0

有趣的相同和'java'代碼html'代碼示例,但它不可能得到,而不該指數?我的意思是。沒有屬性.index = ... – goran

+0

你可以通過如下路徑:driver.findElement(By.xpath(「// table [@ class ='table-hover tablesorter ib-table'] // th [ 1]「))的getText。如果它的幫助 –

0

這不會在奇數工作例如使用colspan時。它應該適用於任何「正常」數據表。修剪用於避免出現在許多WebElements周圍的不可避免的空白。

public static List<WebElement> getColumnByHeaderText(WebDriver driver, By by, String header) { 
    WebElement table = driver.findElement(by); 
    Function<WebElement, String> elementToString = (WebElement w) -> w.getText().trim(); 
    List<WebElement> list = table.findElements(By.tagName("th")); 
    int index = Lists.transform(list, elementToString).indexOf(header); 
    if (index == -1) { 
     throw new RuntimeException("Unable to locate header"); 
    } else { 
     return table.findElements(By.cssSelector("td:nth-child(" + (index + 1) + ")")); 
    } 
}