HTML with jsoup
Another package: parse a page, select with CSS selectors, change it and write it again.
What you will learn#
- parsing HTML text,
- CSS selectors, the same as a browser's,
- reading text and attributes,
- changing the document.
The program#
# Tutorial 14: reading HTML with jsoup - another package of Maven Central
load "java.ring"
jMavenClasses("org.jsoup:jsoup:1.17.2",["org.jsoup","org.jsoup.nodes","org.jsoup.select"])
using {
"org.jsoup"
"org.jsoup.nodes"
"org.jsoup.select"
}
Jsoup = new Jsoup
cHtml = '
<html><head><title>Books</title></head><body>
<h1>Ring books</h1>
<ul id="list">
<li class="book"><a href="/ring-intro">Introduction</a> <span class="price">9.50</span></li>
<li class="book"><a href="/ring-java">Ring and Java</a> <span class="price">12.00</span></li>
<li class="other"><a href="/blog">Blog</a></li>
</ul>
<p>Total <b>2</b> books</p>
</body></html>'
oDoc = Jsoup.parse(cHtml)
? oDoc.title(NULL)
? oDoc.select("h1").text()
# CSS selectors: the same ones that a browser uses
aBooks = oDoc.select("li.book").toList()
for oBook in aBooks
? oBook.select("a").text() + " -> " + oBook.select("a").attr("href") + " : " + oBook.select(".price").text()
next
? oDoc.select("li").size()
? oDoc.select("ul#list > li.book").size()
# the sum of the prices
nTotal = 0
aPrices = oDoc.select("span.price").toList()
for oPrice in aPrices
nTotal += 0 + oPrice.text(NULL)
next
? nTotal
# changing the document and writing it again
oDoc.select("h1").first().text("Ring and Java books")
oDoc.select("p").remove(NULL)
? oDoc.select("body").html(NULL)Books
Ring books
Introduction -> /ring-intro : 9.50
Ring and Java -> /ring-java : 12.00
3
2
21.50
<h1>Ring and Java books</h1>
<ul id="list">
<li class="book"><a href="/ring-intro">Introduction</a> <span class="price">9.50</span></li>
<li class="book"><a href="/ring-java">Ring and Java</a> <span class="price">12.00</span></li>
<li class="other"><a href="/blog">Blog</a></li>
</ul>How it works#
Jsoup.parse(html) gives a Document. select("li.price") returns the elements that match a CSS selector, and text(), attr("href") read them. text("...") changes an element, remove() deletes the selected ones, and html() writes the document again.
Exercises#
- List all the links of a page.
- Add a class to every row of a table.
- Sum a column of prices.