gpt4 book ai didi

java - 如何修复此 jsoup 元素 nullpointerException

转载 作者:太空宇宙 更新时间:2023-11-04 07:32:47 25 4
gpt4 key购买 nike

更新:谢谢大家都接受了 zEro 答案,它似乎解决了我的问题,而且很好很整洁。

大家好,我现在正在使用 jsoup 做一些工作,并从页面中抓取一些数据......

我似乎遇到了一个问题,该代码块抛出空指针异常

Element imagelink;
imagelink = post.getElementsByClass("separator").first().getElementsByTag("img").first();
if(imagelink != null){
if(imagelink.attr("src") != null){
imageURL = imagelink.attr("src");
}else{
imageURL = "http://img27.imageshack.us/img27/1209/k0ve.jpg";
}
}else{
imageURL = "http://img27.imageshack.us/img27/1209/k0ve.jpg";
} }`

我尝试调整语句以避免空指针,但我似乎无法摆脱它。

大家有什么想法吗?

更新:

这似乎是由于我正在抓取的页面具有非常草率的 HTML,有些标签存在,有些标签不存在......

为了解决这个问题,我必须运行大量的陷印来确保所有元素都存在......我已经想出了这个,但如果有人能看到一种简化的编写方式,我会很高兴。 (因为我对java还很陌生)

Element imagelink;
imagelink = post.getElementsByClass("separator").first();
if(imagelink != null){
imagelink = imagelink.getElementsByTag("img").first();
if(imagelink !=null){
if(imagelink.attr("src") != null){
imageURL = imagelink.attr("src");
}else{
imageURL = "http://img27.imageshack.us/img27/1209/k0ve.jpg";
}
}else{
imageURL = "http://img27.imageshack.us/img27/1209/k0ve.jpg";
}
}else{
imageURL = "http://img27.imageshack.us/img27/1209/k0ve.jpg";
}

最佳答案

试试这个:

String imageURL;

if(post == null || post.select(".separator img[src]").isEmpty())
imageURL = "http://img27.imageshack.us/img27/1209/k0ve.jpg";
else
imageURL = post.select(".separator img[src]").first().attr("src");

阅读有关 Jsoup selector syntax here 的更多信息。

关于java - 如何修复此 jsoup 元素 nullpointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17438451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com