按标题选择列



在我的脚本(Selenium和Java)中,我需要通过标题选择一个表列。基本上,我将标头作为参数发送,然后通过该列获取。

但是,问题是我无法获取标题列的索引。有什么想法或建议吗?

 <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">

首先,您需要创建一个包含所有标题

的列表
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...
}

这在奇数情况下不起作用,例如使用 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 ) + ")"));
    }
}

最新更新