如何修复这个jsoup元素nullpointerexception

时间:2013-07-03 01:44:21

标签: java jsoup

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

嘿大家我现在正在和jsoup一起工作并从网页上抓取一些数据......

我似乎遇到了这个代码块抛出nullpointerexception的问题

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";
                        }

1 个答案:

答案 0 :(得分:1)

试试这个:

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上阅读更多内容。