Jsoup get links from HTML example

Let us discuss how to get links from HTML using Jsoup API with the help of below example.

Follow the below steps:

1. Use connect(String url) method of Jsoup class which returns the connection of specified URL.
2. Use get() method of Connection class which returns Document object.
3. Get links from document object.
4. Iterate the links.
5. Print link attributes.

Example:

JsoupGetLinks.java

import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
/**
 * This class is used get links from HTML using Jsoup.
 * @author javawithease
 */
public class JsoupGetLinks {
  public static void main(String args[]){
    Document document;
    try {
    	//Get Document object after parsing the html from given url.
	document = Jsoup.connect("http://tutorialspointexamples.com/").get();
 
	//Get links from document object. 
	Elements links = document.select("a[href]");
 
	//Iterate links and print link attributes.
	for (Element link : links) {
		System.out.println("Link: " + link.attr("href"));
		System.out.println("Text: " + link.text());
		System.out.println("");
	}
 
    } catch (IOException e) {
	e.printStackTrace();
    }		
  }
}

Output:

Link: http://tutorialspointexamples.com
Text: Javawithease
 
Link: http://tutorialspointexamples.com/
Text: Home
 
Link: http://tutorialspointexamples.com/core-java-tutorial/
Text: Core Java
 
Link: http://tutorialspointexamples.com/servlet-tutorial/
Text: Servlet
 
Link: http://tutorialspointexamples.com/jsp-tutorial/
Text: JSP
 
Link: http://tutorialspointexamples.com/struts-2-tutorial/
Text: Struts2
 
Link: http://tutorialspointexamples.com/hibernate-tutorial/
Text: Hibernate
 
Link: http://tutorialspointexamples.com/java-mail-api-tutorial/
Text: Java Mail
 
Link: http://tutorialspointexamples.com/quartz-scheduler-tutorial/
Text: Quartz Scheduler
...

Download this example.
 
Next Topic: Jsoup get images from HTML example.
Previous Topic: Jsoup get title from HTML example.

Related Topics:

How to build java project using ant in eclipse?
JAXB marshalling – convert java object to xml example.
How to create pdf file in java using iText jar?
Generics class example.
OGNL in struts 2.
Hibernate One-to-One Mapping using xml.
Send inline image in email using JavaMail API.
Quartz 2 JobListener example.