【问题标题】:Differenciate <img> with no "alt" and <img> with empty "alt" attribute with JSoup使用 JSoup 区分不带“alt”的 <img> 和带空“alt”属性的 <img>
【发布时间】:2018-03-22 11:25:13
【问题描述】:

我有这个方法试图计算没有任何 alt 属性的图像(甚至没有 alt='')。

private int countImagesWithoutAlt(String page){
    int nbImages = 0;
    int nbImagesWithoutAlt = 0;
    try {
        Document dom = Jsoup.connect(page).get();
        Elements images = dom.getElementsByTag("img");
        nbImages = images.size();
        for (Element image : images) {
            if(image.attr("alt") == null){
                nbImagesWithoutAlt ++;
            }
        }
        return nbImagesWithoutAlt ;
    } catch (IOException e) {
        System.out.println("Problem on " + page + " : " + e);
        return 0;
    }
}

问题是,即使我有&lt;img src="blabla"/&gt;,条件image.attr("alt") == null 也是假的。怎么来的?以及如何修复此代码?

非常感谢。

对于那些想知道为什么我想区分没有“alt”和空“alt”属性的人。在我的上下文中(可访问性测试),“alt”属性是否为空并不总是很重要。这可能意味着图像只是装饰性的,不需要描述。但是,如果根本没有“alt”属性,屏幕阅读器很可能会说“image”,这与使用它的人无关。

【问题讨论】:

    标签: java html web-scraping jsoup


    【解决方案1】:

    好吧,我找到了办法!

    private String countImagesWithoutAlt(String page){
        try {
            Document dom = Jsoup.connect(page).get();
            Elements images = dom.getElementsByTag("img");
            int nbImages = images.size();
            Elements imagesWithoutAlt = dom.getElementsByTag("img").not("[alt]");
            int nBImagesWithoutAlt = imagesWithoutAlt.size();
            return page + "," + nbImages + "," + nBImagesWithoutAlt;
        } catch (IOException e) {
            System.out.println("Problem on " + page + " : " + e);
            return null;
        }
    }
    

    有趣的部分是:

    Elements imagesWithoutAlt = dom.getElementsByTag("img").not("[alt]");

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-20
      • 2021-08-05
      • 2018-03-24
      • 1970-01-01
      相关资源
      最近更新 更多