区分<img/>没有“alt”和<img/>与JSoup的空“alt”属性

时间:2018-03-22 00:05:46

标签: java html web-scraping jsoup

我有这种方法试图计算没有任何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;
    }
}

问题是,即使我有<img src="blabla"/>,条件image.attr("alt") == null也是假的。怎么会?我该如何修复此代码?

非常感谢。

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

1 个答案:

答案 0 :(得分:0)

好吧我找到了办法!

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]");