我正在尝试提取一些汽车广告的img链接。我对此有疑问,因为图片是可选图片,我真的无法检查广告是否包含图片。例如,假设我有以下广告:
这是我的代码:
for (Element searchResult : page2.select(".offer-wrapper > table > tbody > tr > td > a > img")) {
img = searchResult.attr("src");
list.get(index).setImgLink(img);
index++;
}
基本上,searchResult永远不会为空,它将仅找到2个图像源,第二个广告将获取第三个图像的图像。我该如何处理,还找到一种方法来检查第二个广告是否包含图像? 我还尝试检查img变量是否为空或为null,但它只会返回第一次添加和第三次添加的源图像。
答案 0 :(得分: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++;
}