简体   繁体   中英

how to fix this jsoup element nullpointerexception

UPDATE: Thanks everyone accepted zEro answer it seemed to fix my problem and is nice and neat.

Hey everyone I am doing some work with jsoup at the moment and am scraping some data from pages...

I seem to be having an issue where this block of code throws a 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";
}                           }`

I have tried to condition the statements as to avoid a null pointer, but I can't seem to get rid of it.

Anyone have any ideas?

Update:

This seems to be due to the page I am scraping having very sloppy HTML some tags are there and some tags are not...

to fix this I had to run a lot of trapping to make sure all elements existed... I have come up with this but would love if some one can see a simplified way of writing it. (as I am fairly new to 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";
                        }

Try this:

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

Read up more on the Jsoup selector syntax here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM