jsoup - Extract Text

Following example will showcase use of methods to get text after parsing an HTML String into a Document object.


Document document = Jsoup.parse(html);
Element link = document.select("a").first();     
System.out.println("Text: " + link.text());


  • document − document object represents the HTML DOM.

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

  • html − HTML String.

  • link − Element object represent the html node element representing anchor tag.

  • link.text() − text() method retrives the element text.


Element object represent a dom elment and provides various method to get the text of a dom element.


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


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

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>"
      Document document = Jsoup.parse(html);

      //a with href
      Element link = document.select("a").first();         

      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.

Text: Google