【问题标题】:selenium how to know if one element has a href link or not,if not continue the testselenium如何知道一个元素是否有href链接,如果没有继续测试
【发布时间】:2019-07-04 19:28:59
【问题描述】:

我正在使用 selenium java 3.141.59 和 testng 6.14.3。
测试页面可能显示如下

<tbody>
  <tr>
    <td class="S_line1">
      <strong class="W_f12">82</strong>
      <span class="S_txt2">fans</span>
    </td>
  </tr>
</tbody>

<tbody>
  <tr>
    <td class="S_line1">
      <a bpfilter="page_frame" class="t_link S_txt1" href="//xx.com/p/1003061291477752/follow?from=page_100306&amp;wvr=6&amp;mod=headfollow#place">
        <strong class="W_f12">170</strong>
        <span class="S_txt2">fans</span>
      </a>
    </td>
  </tr>
</tbody>

如果“粉丝”有href链接,那么我会点击“粉丝”链接。如果没有,我将跳过这一步并继续做其他人。
ExpectedConditions.presenceOfElementLocated 不适用于这种情况,因为它会在找不到href链接并停止测试时抛出异常。

【问题讨论】:

标签: java selenium


【解决方案1】:

为了检查节点 href 是否存在,您可以使用下面的 XPath 来识别 a 节点,因为 href 存在于 a 内部(我假设该类在这里是唯一的,如果没有,则使用其他定位器并在末尾附加//a):

String xpath = "//td[@class=\"S_line1\"]/a"

你可以像下面这样检查它的存在:

List<WebElement> hrefs = driver.findElements(By.xpath(xpath));
if(hrefs.size() > 0) {
    System.out.println("=> The href is present...");
    hrefs.get(0).click();
} else {
    System.out.println("=> The href is not present...");
}

如果href 不存在,上面的代码不会抛出任何错误。所以你不需要在那里处理任何异常。

希望对你有帮助……

【讨论】:

  • 这也是一个好方法...查看我的答案,它只会找到fans...的链接文本...你怎么看?
  • 是的@Moshe Slavin,但是如果预期值不存在并且你用try-catch 块包装它,这是已知的选项,所以我尝试了不同的方法 - 你的仍然很好接近...
【解决方案2】:

下面的代码首先在表格中找到所有&lt;a&gt;标签,如果标签有href,就会一一点击:

List<WebElement> allAnchorElements = driver.findElements(By.xpath("//table//td[@class='S_line1']/a"));

for(WebElement currElem : allAnchorElements ){

     if(currElem.getAttribute("href")){

           currElem.click();
     }

}

【讨论】:

    【解决方案3】:

    您只查找具有hreffans 元素...

    我能想到的最好方法是使用By.linkText()

    在你的情况下:

    try{
        WebElement link  = driver.findElement(By.linkText("fans"));
        System.out.println(link.getAttribute("href"));
        link.click();
        }
    catch(NoSuchElementException e){
            System.out.println(e);
        }
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-10
      • 2021-11-22
      • 2015-12-02
      • 1970-01-01
      相关资源
      最近更新 更多