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

使用Jsoup区分无alt属性与alt为空的<img>标签及计数问题

解决Jsoup统计无alt属性图片的问题

我来帮你搞定这个统计问题!你当前的代码没法正确统计目标图片数量,核心原因是没搞清楚Jsoup处理元素属性的逻辑:

Jsoup的Element.attr("alt")方法永远不会返回null——不管元素有没有alt属性,它都会返回字符串:

  • 如果元素完全没有alt属性,返回空字符串""
  • 如果元素有alt属性但值为空(比如<img alt=''/>),也返回空字符串""

所以你用image.attr("alt") == null的判断逻辑完全起不到区分作用,这就是统计不准的根源。

正确的判断逻辑

要精准区分两种情况,得用Jsoup提供的专属方法:

  • 完全没有alt属性:用!image.hasAttr("alt")
  • 有alt属性但值为空:用image.hasAttr("alt") && image.attr("alt").isEmpty()

修正后的代码

private int countImagesWithoutAlt(String page){
    int nbImagesWithoutAlt = 0;
    try {
        Document dom = Jsoup.connect(page).get();
        Elements images = dom.getElementsByTag("img");
        
        for (Element image : images) {
            // 仅统计完全没有alt属性的图片
            if(!image.hasAttr("alt")){
                nbImagesWithoutAlt ++;
            }
        }
        return nbImagesWithoutAlt ;
    } catch (IOException e) {
        System.out.println("Problem on " + page);
        // 建议返回明确错误值,避免调用方处理异常情况的空值
        return -1;
    }
}

额外扩展:同时统计两种情况

如果需要同时统计「无alt属性」和「alt属性为空」的图片数量,可以用这段代码:

private void countImageAltStatus(String page){
    int noAltAttr = 0;
    int emptyAltValue = 0;
    try {
        Document dom = Jsoup.connect(page).get();
        Elements images = dom.getElementsByTag("img");
        
        for (Element image : images) {
            if(!image.hasAttr("alt")){
                noAltAttr++;
            } else if(image.attr("alt").isEmpty()){
                emptyAltValue++;
            }
        }
        System.out.println("完全无alt属性的图片数量:" + noAltAttr);
        System.out.println("有alt但值为空的图片数量:" + emptyAltValue);
    } catch (IOException e) {
        System.out.println("Problem on " + page);
    }
}

内容的提问来源于stack exchange,提问作者Zoette

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 12:14:23