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

标签 javascript html xpath selenium-webdriver webdriver

我正在使用网络驱动程序,需要检查数据表是否包含我想要的值,并可能单击链接?
我想它应该与 xpath 一起工作?

例如: 我的网络应用程序的数据表有 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”元素。但正如您所看到的,所有标签td都没有文本。它的标签是a who has text。所以需要归档标签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");
            }
        }

关于javascript - 如何检查数据表是否包含我想要的值并可能单击链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338244/

相关文章:

Javascript - 日期范围验证

javascript - 如何在javascript中更改下拉框值时获取文本框值

javascript - 菜单边框,当前菜单边框 css

javascript - JS : 'this' collision in unit test for publication?

javascript - 脚本在 safari 中不起作用

html - Orbeon Form Runner iFrame 问题

javascript - 无法使功能自动刷新

java - 将元素添加到文档并使用 XPath 查找

java - XPath 在java中选择文档中具有指定名称的所有节点

jquery - 使用 jQuery 抓取 HTML 文档,这可能吗?