Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jsoup select and iterate all elements

Tags:

java

jsoup

I will connect to a url through jsoup and get all the contents of it but the thing is if I select like,

doc.select("body")

its returning a single element but I want to get all the elements in the page and iterate them one by one for example,

<html>
<head><title>Test</title></head>
<body>
<p>Hello All</p>
<a href="test.html">Second Page</a>
<div>Test</div>
</body>
</html>

If I select using body I am getting the result in a single line like,

Test Hello All Second Page Test

Instead I want to select all elements and iterate one by one and produce the results like,

Test
Hello All
Second Page
Test

Will that be possible using jsoup?

Thanks,
Karthik

like image 889
Karthik Avatar asked Aug 12 '11 06:08

Karthik


2 Answers

You can select all elements of the document using * selector and then get text of each individually using Element#ownText().

Elements elements = document.body().select("*");

for (Element element : elements) {
    System.out.println(element.ownText());
}
like image 61
BalusC Avatar answered Nov 13 '22 14:11

BalusC


To get all of the elements within the body of the document using jsoup library.

doc.body().children().select("*");

To get just the first level of elements in the documents body elements.

doc.body().children();

like image 20
Blind TeamKiller Avatar answered Nov 13 '22 13:11

Blind TeamKiller