English 中文(简体)
jsoup - Using Selector Syntax
  • 时间:2024-12-22

jsoup - Using Selector Syntax


Previous Page Next Page  

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 pnks = 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".

    pnks − 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;

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

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

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

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

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

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

      for (Element pnk : sampleLinks) {
         System.out.println("Text: " + pnk.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