Extracting data using CSS selector (Must know)

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.

Getting ready

If you don't know the CSS selector syntax yet, I suggest finding some tutorials or guidelines to learn about it first.

Note

The following two links will be helpful for you to learn about CSS selector syntax:

How to do it...

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.

  1. Create the Document class structure by loading the URL:
    Document doc = Jsoup.connect(mUrl).get();
  2. Select the <div> tag with the class attribute nav-sections:
    Elements navDivTag = doc.select("div.nav-sections");
  3. Select all the <a> tags:
    Elements list = navDivTag.select("a");
  4. 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 sourceSection03.

How it works...

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.

There's more...

Please refer to the following pages for the usage of all CSS selector syntax to use in your application:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.68.81