Book Image

Instant jsoup How-to

By : Pete Houston
Book Image

Instant jsoup How-to

By: Pete Houston

Overview of this book

As you might know, there are a lot of Java libraries that support parsing HTML content out there. Jsoup is yet another HTML parsing library, but it provides a lot of functionalities and boasts much more interesting features when compared to others. Give it a try, and you will see the difference! Instant jsoup How-to provides simple and detailed instructions on how to use the Jsoup library to manipulate HTML content to suit your needs. You will learn the basic aspects of data crawling, as well as the various concepts of Jsoup so you can make the best use of the library to achieve your goals. Instant jsoup How-to will help you learn step-by-step using real-world, practical problems. You will begin by learning several basic topics, such as getting input from a URL, a file, or a string, as well as making use of DOM navigation to search for data. You will then move on to some advanced topics like how to use the CSS selector and how to clean dirty HTML data. HTML data is not always safe, and because of that, you will learn how to sanitize the dirty documents to prevent further XSS attacks. Instant jsoup How-to is a book for every Java developer who wants to learn HTML manipulation quickly and effectively. This book includes the sample source code for you to refer to with a detailed explanation of every feature of the library.
Table of Contents (7 chapters)

Listing all images within an HTML page (Should know)

Another well-known example of data parsing tasks nowadays is image crawling. Let's try to do it with Jsoup parser.

How to do it...

In this task, we're going to parse a few images from,

  1. Load the Document class structure from the page.

    Document doc = Jsoup.connect(URL_SOURCE).get();
  2. Select the images.

    Elements links ="img[src]");
  3. Output the results.

    for(Element url: links) {
    System.out.println("* " + url.attr("abs:src"));

The complete example source code for this section is available at \source\Section07.

How it works...

In HTML, the images are usually put under the <img> tag, so the selector to query these images is img[src]:

Elements links ="img[src]");

However, if the image is defined as a CSS attribute, it is out of the Jsoup role,which is used purely to parse the HTML result.