How can I get all div elements using jsoup?

I am learning how to use jsoup. At first I thought jsoup was like jquery, but it is not.

I want to extract this html body into div elements.

<html>
<head></head>
    <body>
            <div>
                <h1>Title</h1>
            </div>
            <div>
                <img src="/xx.jpg" />
            </div>
            <div>
                <p>Paragraph 1</p>
                <p>Paragraph 2</p>
            </div>
            <div>
                <h2><b>End</b></h2>
            </div>
        </body>
</html>

I am using this code:

Document doc = Jsoup.parse(htmlString);
Elements divs = doc.select("div");

but it returns all div. I want the elements to be returned like this:

divs.get(0).toString(); // "<h1>Title</h1>"
divs.get(1).toString(); // "<img src="/xx.jpg" />"
divs.get(2).toString(); // "<p>Paragraph 1</p><p>Paragraph 2</p>"
divs.get(3).toString(); // "<h2><b>End</b></h2>"

Help me in getting divs to elements with jsoup and get back as above?

+4
source share
2 answers

Make divs .get (0) .html ();

It will provide you an internal html tag

+3
source

Using . html () will retrieve the internal html.

Document doc = Jsoup.parse(htmlString);
Elements divs = doc.select("div");
//divs.get(0).html();
for(Element elem : divs){
  System.out.println(elem.html()); //get all elements inside div
}

If you want to include a div, you can use . outerHtml () .

+4
source

All Articles