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 ... |
No comments:
Post a Comment