Instead of using DOM navigation, the CSS selector method is used. Basically, the CSS selector is the way to identify the element based on how it is styled in CSS. Let's see how this works.
If you don't know the CSS selector syntax yet, I suggest finding some tutorials or guidelines to learn about it first.
Now we will try to use CSS selector syntax to do the same task that DOM navigation does. Basically, it is the same code as in the previous recipe but is a little different in the way we parse the content.
Create the
Document
class structure by loading the URL:Document doc = Jsoup.connect(mUrl).get();
Select the
<div>
tag with the class attributenav-sections
:Elements navDivTag = doc.select("div.nav-sections");
Select all the
<a>
tags:Elements list = navDivTag.select("a");
Retrieve the results from the list:
for(Element menu: list) { System.out.print(String.format("[%s]", menu.html())); }
As you try to execute this code, it will produce the same result as the previous recipe by using DOM navigation.
The complete example source code for this section is available at \source\Section03
.
It works like a charm! Well, there is actually no magic here. It's just that the selector query will give the direction to the target elements and Jsoup will find it for you. The select()
method is written for this task so that you don't have to care a lot about it.
Through the query doc.select("div.nav-sections")
, the Document
class will try to find and return all the <div>
tags that have class name equal to nav-sections
.
It is even simpler when trying to find the children; Jsoup will look up every child and their children to find the tags that match the selector. That's how all the <a>
tags are selected in step 3. Compared to DOM navigation, it is much simpler to use and easier to understand. Developers should know HTML page structure in order to use the CSS selector query.
Please refer to the following pages for the usage of all CSS selector syntax to use in your application: