Jsoup Example: print links of an URL

Jsoup example: print links of an url tutorial for beginners and professionals, jsoup - java html parser providing facility to parse html document by java language with examples of printing title, links, images, form elements from url.

Jsoup Example: print links of an URL

Jsoup Example: print links of an URL

In this example, we will print the total links of an URL. To do so, we are going to call select() method of Document class that returns the reference of Elements. The Elements class have elements that can be traversed by for-each loop. The Element class provides attr() and text() methods to return link and text of the link.

  1. import java.io.IOException;  
  2. import org.jsoup.Jsoup;  
  3. import org.jsoup.nodes.Document;  
  4. import org.jsoup.nodes.Element;  
  5. import org.jsoup.select.Elements;  
  6. public class JsoupPrintLinks {  
  7.      public static void main( String[] args ) throws IOException{  
  8.             Document doc = Jsoup.connect("http://www.tpoint.com").get();  
  9.             Elements links = doc.select("a[href]");  
  10.             for (Element link : links) {  
  11.                 System.out.println("\nlink : " + link.attr("href"));  
  12.                 System.out.println("text : " + link.text());  
  13.             }  
  14. }  
  15. }  

Output:

link : http://www.tpoint.com/contribute-us
text : Contribute Us

link : http://www.tpoint.com/asknewquestion.jsp
text : Ask Question

link : http://www.tpoint.com/login.jsp
text : login

.....