1

I am trying to get the content from <div class="article__content"> but I got NullPointerException, I dont really know how to solve this as I dont have that much web knowledge maybe I am using the tags incorrectly :/ Here is my code:

public static void main(String []args) throws IOException {
        Document doc = Jsoup.connect("somelink").get();

        String content = doc.getElementById("article__content").text();
       System.out.println(content);
    }
3
  • 1
    You actually should provide more information, such as where the exception ocurrs, a stacktrace, etc. Commented Jan 31, 2016 at 10:54
  • 1
    You said you want to get a div by its class but you are calling getElementById, not getElementsByClass. Could that be where the problem lies? Commented Jan 31, 2016 at 10:56
  • @Sam thank you :)) That was the problem, I didnt notice that it was getElementById :/ Commented Jan 31, 2016 at 11:00

2 Answers 2

1

you need to use the getElementsByClass function:

Elements articles = doc.getElementsByClass("article__content");

As there can be more than one div having this class, this function returns an "Elements" object. If you know for shure that there is just one object with this class, you can use this:

Element article = doc.getElementsByClass("article__content").first();

So if you want to return the text that is written between the <div> tags, you just use the text() function. So it would look like this:

System.out.println(article.text());
Sign up to request clarification or add additional context in comments.

Comments

1

Alternatively, if you have control over the HTML and there is only one of the element in question, rewrite the HTML to use the id attribute instead of class. Using class when there is guaranteed to be only one element of the class is not recommended practice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.