
- Jsoup Tutorial
- jsoup - Home
- jsoup - Overview
- jsoup - Environment Setup
- Examples - Input
- jsoup - Parsing String
- jsoup - Parsing Body
- jsoup - Loading URL
- jsoup - Loading File
- Examples - Extracting Data
- jsoup - Using DOM Methods
- jsoup - Using Selector Syntax
- jsoup - Extract Attributes
- jsoup - Extract Text
- jsoup - Extract HTML
- jsoup - Working with URLs
- Examples - Modifying Data
- jsoup - Set Attributes
- jsoup - Set HTML
- jsoup - Set Text Content
- Examples - Cleaning HTML
- jsoup - Sanitize HTML
- jsoup Useful Resources
- jsoup - Quick Guide
- jsoup - Useful Resources
- jsoup - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
jsoup - Extract Attributes
Following example will showcase use of method to get attribute of a dom element after parsing an HTML String into a Document object.
Syntax
Document document = Jsoup.parse(html); Element link = document.select("a").first(); System.out.println("Href: " + link.attr("href"));
Where
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.attr() − attr(attribute) method retrives the element attribute.
Description
Element object represent a dom elment and provides various method to get the attribute of a dom element.
Example
Create the following java program using any editor of your choice in say C:/> jsoup.
JsoupTester.java
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>" +"</div>" +"</body></html>"; Document document = Jsoup.parse(html); //a with href Element link = document.select("a").first(); System.out.println("Href: " + link.attr("href")); } }
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.
Href: www.google.com
Advertisements