我如何检查数据表是否包含我想要的值,并可能单击链接

How can I check if the Data table contains the value I want and possibly click on the link?

本文关键字:链接 单击 我想要 包含 何检查 检查 是否 数据表      更新时间:2023-09-26

我正在使用web驱动程序,需要检查数据表是否包含我想要的值,并可能点击链接?
我想应该可以用xpath吧?

例如

:我有一个web应用程序,有数据表与3列,其中

<div id="studyResultsId">
  <tbody><tr>
    <td><a href="/portal/study/studyAction!view.action?studyId=STUDY0000222">Using Automation</a></td>
  </tr>
  <tr>
    <td><a href="/portal/study/studyAction!view.action?studyId=STUDY0000281">Using Design</a></td>
  </tr>
  <tr>
    <td><a href="/portal/study/studyAction!view.action?studyId=STUDY0000272">Using Development</a></td>
  </tr>
</tbody>

我尝试了以下操作,但没有成功:

    String abc = driver.findElement(By.xpath(".//*[@id='studyResultsId']/div/table/tbody/tr/td")).getText();
    //Retrieving the data from the Td of table in to a string
    if(abc.contains("Automation")) {
        System.out.println("contains Automation");
    } else {
        System.out.println("does not contains Automation");
    }
}

根据你的html,我想先谈谈你的xpath,

driver.findElement(By.xpath(".//*[@id='studyResultsId']/div/table/tbody/tr/td")).getText();

下一行中的字符串'foo'是您可以通过上面的xpath得到的。

<div id="studyResultsId'><div><table><tbody><tr><td>foo</td></tr></tbody></table></div></div>

回到你的html。基本上当你通过id='studyResultsId'搜索时,你已经访问了第一个div标签。所以不需要第二个'/div'了。然后你试着找到'td',是的,在当前的情况下,你得到了第一个'td'元素。但是正如您所看到的,所有的标签都没有文本。这是标签a谁有文本。所以你需要存档标签a并遍历它。下面的代码是我的建议

//Initilize your webdriver first
List<WebElement> wl = driver.findElements(By.xpath("//div[@id='studyResultsId']//a"));
        for(int i=0; i<wl.size(); i++) {
            WebElement current = wl.get(i);
            if(current.getText().contains("Automation")) {
                System.out.println("Current tag '" + current.getText() + "' has text Automation");
            }  else {
                System.out.println("Current tag '" + current.getText() + "' has no text Automation");
            }
        }

j.l u和sideshowbarker已经为您的XPath表达式提供了简明的建议,我将拒绝提供其他建议,但是为了简洁起见,这里是我如何使用其他定位器定位所需的链接WebElement:

首先,我将使用它的id属性定位表WebElement:

WebElement table = driver.findElement(By.id("studyResultsId"));

现在有两种方法可以用来定位所需的链接:

  1. By Partial Link Text -

    // This will return all link WebElements within the table
    // that have partial matching visible text.
    List<WebElement> matchingLinks = table.findElements(By.partialLinkText("Automation"));
    
  2. 按标签名称-

    // This will return all link WebElements within the table
    List<WebElement> tableLinks = table.findElements(By.tagName("a"));
    

    要识别这些链接元素中哪些包含文本"Automation",您可以使用标准的Java表达式,如下所示:

    List<WebElement> matchingLinks = new ArrayList<>();
    for (WebElement link : tableLinks) {
       if (link.contains("Automation")) {
          matchingLinks.add(link);
       }
    }
    

你可以根据需要使用matchingLinks列表中的任意一个。