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

时间:2015-09-01 18:08:40

标签: 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");
    }
}

2 个答案:

答案 0 :(得分:2)

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

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

String&#39; foo&#39;在以下行中,您可以通过上面的xpath获得。

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

回到你的HTML。基本上当你通过id =&#39; studyResultsId&#39;进行搜索时你已经访问了第一个div标签。因此,不需要第二个&#39; / div&#39;再次。然后你试图找到“td&#39;”,是的,在目前的情况下,你得到了第一个&#39; td&#39;元件。但正如您所看到的,所有标记 td 都没有文本。它标记了一个有文字的人。因此,您需要归档标记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");
            }
        }

答案 1 :(得分:2)

由于J.Lyu和sideshowbarker已经为你的XPath表达提供了简明的建议,我将拒绝提供另一个,但为了简洁起见,我将如何使用其他定位器找到所需的链接WebElement:

首先,我将首先使用id attribute

查找表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. By Tag Name -

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

    要确定哪些链接元素包含“自动化”文本,您可以使用标准的Java表达式,如下所示:

    List<WebElement> matchingLinks = new ArrayList<>();
    
    for (WebElement link : tableLinks) {
       if (link.contains("Automation")) {
          matchingLinks.add(link);
       }
    }
    
  3. 然后,您可以根据需要使用matchingLinks WebElements列表。