[英]how to fix this jsoup element nullpointerexception
更新:谢谢大家接受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";
}
尝试这个:
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选择器语法的更多信息 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.