You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IsDisplayed()方法未返回布尔值反而抛出NoSuchElementException问题

问题分析

首先你的代码存在两处语法错误,需要先修正:

  • lib.isDisplayed()方法定义错误,参数列表多了一对括号,正确写法是public static boolean isDisplayed(WebElement locator)
  • icon方法里的driver.findElement.(By.xpath(...))多了个点,应该是driver.findElement(By.xpath(...))

即便修正了语法,你遇到的NoSuchElementException也不是来自isDisplayed()方法的异常捕获逻辑——问题出在调用icon("123456789")的时候:driver.findElement()在找不到目标元素时会直接抛出NoSuchElementException,这时候代码还没进入到isDisplayed()的try-catch块,自然无法返回false。

解决方案

有两种实用的解决方式:

方式一:在icon方法中处理元素查找异常

修改icon方法,让它在找不到元素时返回null而非抛出异常,同时给isDisplayed()方法增加null判断:

// 修改后的icon方法
public WebElement icon(String rootnumber){
    try{
        return driver.findElement(By.xpath("//div[@row_id='"+rootnumber+"']//following-sibling::span[@matbadgecolor='warn']"));
    } catch (NoSuchElementException e){
        return null;
    }
}

// 修改后的isDisplayed方法
public static boolean isDisplayed(WebElement locator){
    if(locator == null){
        return false;
    }
    try{
        return locator.isDisplayed();
    }catch (Exception e){
        return false;
    }
}

方式二:将元素定位与显示判断整合到一个方法

直接把定位器(By对象)传入isDisplayed方法,在方法内部完成元素查找和显示状态判断,这样所有异常都能被统一捕获:

// 修改后的isDisplayed方法,接收By类型参数
public static boolean isDisplayed(By locator){
    try{
        return driver.findElement(locator).isDisplayed();
    }catch (Exception e){
        return false;
    }
}

// 调用方式调整
By iconLocator = By.xpath("//div[@row_id='123456789']//following-sibling::span[@matbadgecolor='warn']");
System.out.println("Boolean value of icon presence is "+lib.isDisplayed(iconLocator));

内容的提问来源于stack exchange,提问作者M Thomas Mary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 04:16:10