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.



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 w3spoint
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("https://www.w3spoint.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());
    } catch (IOException e) {


Link: https://www.w3spoint.com
Text: W3spoint
Link: https://www.w3spoint.com/
Text: Home
Link: https://www.w3spoint.com/core-java-tutorial/
Text: Core Java
Link: https://www.w3spoint.com/servlet-tutorial/
Text: Servlet
Link: https://www.w3spoint.com/jsp-tutorial/
Text: JSP
Link: https://www.w3spoint.com/struts-2-tutorial/
Text: Struts2
Link: https://www.w3spoint.com/hibernate-tutorial/
Text: Hibernate
Link: https://www.w3spoint.com/java-mail-api-tutorial/
Text: Java Mail
Link: https://www.w3spoint.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.


Please Share