Jsoup发现标签是否不存在

问题描述 投票:0回答:1

我正在尝试提取一些汽车广告的img链接。我遇到了这个问题,因为图像是可选的,我真的无法检查广告是否有它的图像。例如,假设我有以下广告:enter image description here

这是我的代码:

for (Element searchResult : page2.select(".offer-wrapper > table > tbody > tr > td > a > img")) {
   img = searchResult.attr("src");
   list.get(index).setImgLink(img);

   index++;
}

基本上,searchResult将永远不会为null,它将只找到2个图像源,第二个广告将获得第三个图像。我如何处理这个并找到一种方法来检查第二个广告是否有图像?我还尝试检查img变量是空还是null但它只返回第一个和第三个添加的源图像。

image jsoup extract
1个回答
0
投票

不要选择a > img,只选择a,然后检查img是否存在:

    Elements searchResults = page2.select(".offer-wrapper > table > tbody > tr > td > a");
    for (Element searchResult : searchResults) {
        Element imgElement = searchResult.select("img").first();
        if (imgElement != null) {
            String imgSrc = imgElement.attr("src");
            list.get(index).setImgLink(imgSrc);
        } else {
            list.get(index).setImgLink(null);
        }
        index++;
    }

编辑:另一种检查图像的方法

你可以观察到olx上没有图像的链接有类nophoto,所以这个也有效:

    Elements searchResults = page2.select(".offer-wrapper > table > tbody > tr > td > a");
    for (Element searchResult : searchResults) {
        boolean withoutImage = searchResult.hasClass("nophoto");
        if (!withoutImage) {
            String imgSrc = searchResult.select("img").first().attr("src");
            list.get(index).setImgLink(imgSrc);
        } else {
            list.get(index).setImgLink(null);
        }
        index++;
    }
© www.soinside.com 2019 - 2024. All rights reserved.