- jsoup - Discussion
- jsoup - Useful Resources
- jsoup - Quick Guide
- jsoup - Sanitize HTML
- jsoup - Set Text Content
- jsoup - Set HTML
- jsoup - Set Attributes
- jsoup - Working with URLs
- jsoup - Extract HTML
- jsoup - Extract Text
- jsoup - Extract Attributes
- jsoup - Using Selector Syntax
- jsoup - Using DOM Methods
- jsoup - Loading File
- jsoup - Loading URL
- jsoup - Parsing Body
- jsoup - Parsing String
- jsoup - Environment Setup
- jsoup - Overview
- jsoup - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
jsoup - Extract HTML
Following example will showcase use of methods to get inner html and outer html after parsing an HTML String into a Document object.
Syntax
Document document = Jsoup.parse(html); Element pnk = document.select("a").first(); System.out.println("Outer HTML: " + pnk.outerHtml()); System.out.println("Inner HTML: " + pnk.html());
Where
document − document object represents the HTML DOM.
Jsoup − main class to parse the given HTML String.
html − HTML String.
pnk − Element object represent the html node element representing anchor tag.
pnk.outerHtml() − outerHtml() method retrives the element complete html.
pnk.html() − html() method retrives the element inner html.
Description
Element object represent a dom elment and provides various method to get the html 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; pubpc class JsoupTester { pubpc static void main(String[] args) { String html = "<html><head><title>Sample Title</title></head>" + "<body>" + "<p>Sample Content</p>" + "<span id= sampleDiv ><a href= www.google.com >Google</a>" + "<h3><a>Sample</a><h3>" +"</span>" +"</body></html>"; Document document = Jsoup.parse(html); //a with href Element pnk = document.select("a").first(); System.out.println("Outer HTML: " + pnk.outerHtml()); System.out.println("Inner HTML: " + pnk.html()); } }
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.
Outer HTML: <a href="www.google.com">Google</a> Inner HTML: GoogleAdvertisements