无法使用带有java的webdriver检索Table th标记值

时间:2018-01-04 07:54:34

标签: java selenium xpath selenium-webdriver

从下面的html我想检查表头值中的每一行,如果匹配需要检索td值

下面是我的HTML

<table class="span-5" id="summaryTable" title="Table showing Summary data">
<tbody>
<tr>
<th class="width-40" id="num">
<a href=" " aria-label=" " title="" class="ui-link">(12) App no</a>:
</th>
<td headers="num">
<a href=" " aria-label=" " title=" " class="ui-link">(11)</a> 
<strong>2796179</strong>
</td>
</tr>
<tr>
<th class="noLines alignLeft width35" id="EnglishTitle"> 
<a href=" " aria-label=" " title=" " class="ui-link">(54) English Title</a>:
</th>
<td class="noLines alignLeft width65" headers="EnglishTitle">
FRAME BIT-SIZE ALLOCATION
</td>
</tr>   
<tr>
</tbody>
</table>

我想收集每个标签值(即(12) App no (54) English Title

我的java代码

WebElement summary = driver.findElement(By.xpath("//*[@id='summaryTable']/tbody"));
                List<WebElement>rows = summary.findElements(By.tagName("tr"));
                for (int i=1;i<=rows.size();i++){

                    String dc = driver.findElement(By.xpath("//*[@id='summaryTable']/tbody/tr["+i+"]/td/th/a")).getText();
                    if (dc.equalsIgnoreCase("(12) App no")){
                         appNo = driver.findElement(By.xpath("//*[@id='summaryTable']/tbody/tr["+i+"]/td/strong")).getText();
                    }                       
                }

但我没有得到这样的元素:无法找到元素:{"method":"xpath","selector":"//*[@id='summaryTable']/tbody/tr[1]/td/th/a"}

4 个答案:

答案 0 :(得分:0)

请使用以下代码

REPLY

答案 1 :(得分:0)

我认为你让它变得有点复杂,你能尝试更简单的版本吗?

public String getRequiredDataFromTableFromRow(String header){
    WebElement table = driver.findElement(By.id("summaryTable"));
    List<WebElement> rows = table.findElements(By.tagName("tr"));
    for (WebElement row:rows) {
        if(row.getText().contains(header)){
           return row.findElement(By.tagName("td")).getText();
        }
    }
    return null;
}

答案 2 :(得分:0)

单元格也是行内的数组,因此您需要指定获取文本的位置。 th标记中没有td标记。

请尝试以下代码:

WebElement summary = driver.findElement(By.xpath("//*[@id='summaryTable']/tbody"));
List<WebElement>rows = summary.findElements(By.tagName("tr"));

for(int i = 1; i <= rows.size(); i++) {

    String dc = driver.findElement(By.xpath("//*[@id='summaryTable']/tbody/tr[" + i + "]/th[0]")).getText();

    if(dc.equalsIgnoreCase("(12) App no")) {
        appNo = driver.findElement(By.xpath("//*[@id='summaryTable']/tbody/tr[" + i + "]/td[0]")).getText();
    }                       
}

答案 3 :(得分:0)

  • 以下基本上是为您提供每个&#34; th&#34;元件。

    WebElement summary = driver.findElement(By.id("summaryTable"));
    List<WebElement>rows = summary.findElements(By.tagName("th"));
    for(WebElement row : rows){
    row.getText();
    }}
    

在上面的代码中,我使用&#34; id&#34;来获取引用。并使用相同的对象引用来获取&#34; th&#34;的元素列表。标签。

如果您想对已发现的文本执行操作,可以使用行元素的引用

来完成