jsoup - Using Selector Syntax



Following example will showcase use of selector methods after parsing an HTML String into a Document object. jsoup supports selectors similar to CSS Selectors.

Syntax

Document document = Jsoup.parse(html);
Element sampleDiv = document.getElementById("sampleDiv");
Elements links = sampleDiv.getElementsByTag("a");

Where

  • document − document object represents the HTML DOM.

  • Jsoup − main class to parse the given HTML String.

  • html − HTML String.

  • sampleDiv − Element object represent the html node element identified by id "sampleDiv".

  • links − Elements object represents the multiple node elements identified by tag "a".

Description

The document.select(expression) method parses the given CSS selector expression to select a html dom element.

Example

Create the following java program using any editor of your choice in say C:/> jsoup.

JsoupTester.java

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class JsoupTester {
   public static void main(String[] args) {
   
      String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<p>Sample Content</p>"
         + "<div id='sampleDiv'><a href='www.google.com'>Google</a>"
         + "<h3><a>Sample</a><h3>"
         +"</div>"
         + "<div id='imageDiv' class='header'><img name='google' src='google.png' />"
         + "<img name='yahoo' src='yahoo.jpg' />"
         +"</div>"
         +"</body></html>";
      Document document = Jsoup.parse(html);

      //a with href
      Elements links = document.select("a[href]");

      for (Element link : links) {
         System.out.println("Href: " + link.attr("href"));
         System.out.println("Text: " + link.text());
      }

      // img with src ending .png
      Elements pngs = document.select("img[src$=.png]");

      for (Element png : pngs) {
         System.out.println("Name: " + png.attr("name"));
      }

      // div with class=header
      Element headerDiv = document.select("div.header").first();
      System.out.println("Id: " + headerDiv.id());
   
      // direct a after h3
      Elements sampleLinks = document.select("h3 > a"); 

      for (Element link : sampleLinks) {
         System.out.println("Text: " + link.text());
      }
   }
}

Verify the result

Compile the class using javac compiler as follows:

C:\jsoup>javac JsoupTester.java

Now run the JsoupTester to see the result.

C:\jsoup>java JsoupTester

See the result.

Href: www.google.com
Text: Google
Name: google
Id: imageDiv
Text: Sample
Advertisements