Parsing HTML

suggest change

HTML in the wild is rarely well-formed: tags aren't closed, attributes aren't quoted, and elements are nested in ways that break the rules. Regular expressions and XML parsers can't cope with that. What you need is an HTML5 parser that repairs broken markup the way browsers do and gives you a DOM to query.

On the JVM the standard choice is jsoup. It's a pure Java library with no dependencies, and Kotlin's null-safety, extension functions and collection operations fit it well.

This article covers:

For downloading pages and crawling, see Web scraping. This article is about what you do with the HTML once you have it.

Setup

Add jsoup to build.gradle.kts:

dependencies {
    implementation("org.jsoup:jsoup:1.23.2")
}

Parsing a string

Jsoup.parse() always gives you a complete Document with <html>, <head> and <body>, even if the input is just a fragment:

import org.jsoup.Jsoup

fun main() {
    val html = """
        <html><head><title>My page</title></head>
        <body><h1>Hello</h1><p>First paragraph.</p></body></html>
    """.trimIndent()

    val doc = Jsoup.parse(html)
    println(doc.title())                     // My page
    println(doc.selectFirst("h1")?.text())   // Hello
    println(doc.body().children().size)      // 2
}

Broken markup gets repaired the same way a browser would repair it:

import org.jsoup.Jsoup

fun main() {
    val doc = Jsoup.parse("<p>One<p>Two<table><td>cell</table><b>unclosed")

    println(doc.select("p").size)                          // 2
    println(doc.select("table > tbody > tr > td").text())  // cell
    println(doc.select("b").text())                        // unclosed
    println(doc.title().isEmpty())                         // true
}

The parser added the missing </p>, <tbody>, <tr> and </b>. That means you can write selectors against the structure a browser would produce, which is what you see in the browser's developer tools.

To parse a snippet of user content meant for a <body>, use parseBodyFragment():

val doc = Jsoup.parseBodyFragment("Some <b>bold</b> text")
val body = doc.body()
println(body.select("b").text())  // bold

Parsing files and HTTP responses

import org.jsoup.Jsoup
import java.io.File

fun main() {
    val file = File("page.html")
    file.writeText("<html><head><meta charset='utf-8'><title>Saved</title></head><body><a href='/about'>About</a></body></html>")

    // pass null as the charset to detect it from <meta charset> (falls back to UTF-8)
    val doc = Jsoup.parse(file, null, "https://example.com/")
    println(doc.title())                              // Saved
    println(doc.selectFirst("a")?.attr("abs:href"))   // https://example.com/about
}

The third argument is the base URI. jsoup uses it to resolve relative links (more on this below). If the page has a <base href> tag, that takes precedence.

If you fetch the page with some other HTTP client, pass the body and the URL to Jsoup.parse(html, baseUri). Here it's done with the JDK's built-in HttpClient (see HTTP client for more options):

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse

val http: HttpClient = HttpClient.newBuilder()
    .followRedirects(HttpClient.Redirect.NORMAL)
    .build()

fun fetchDocument(url: String): Document {
    val request = HttpRequest.newBuilder(URI(url))
        .header("User-Agent", "my-bot/1.0")
        .build()
    val response = http.send(request, HttpResponse.BodyHandlers.ofString())
    check(response.statusCode() == 200) { "HTTP ${response.statusCode()} for $url" }
    // use the final URL after redirects as the base URI
    return Jsoup.parse(response.body(), response.uri().toString())
}

jsoup has its own HTTP client too: Jsoup.connect(url).get(). It's fine for quick scripts.

The DOM: Node, Element, Elements

The main types are:

You can navigate the tree directly:

import org.jsoup.Jsoup

fun main() {
    val doc = Jsoup.parse("""
        <ul id="menu">
          <li>Home</li>
          <li class="active">Docs</li>
          <li>Blog</li>
        </ul>
    """)

    val menu = doc.getElementById("menu")!!
    println(menu.tagName())                            // ul
    println(menu.children().map { it.text() })         // [Home, Docs, Blog]

    val active = menu.getElementsByClass("active").first()!!
    println(active.previousElementSibling()?.text())   // Home
    println(active.nextElementSibling()?.text())       // Blog
    println(active.parent()?.id())                     // menu
    println(active.elementSiblingIndex())              // 1
    println(menu.firstElementChild()?.text())          // Home
}

Methods that might not find anything (getElementById, selectFirst, parent, nextElementSibling) are annotated as nullable, so Kotlin makes you handle the missing case.

Note the difference between childNodes() and children(). The whitespace between <li> tags is made of TextNodes, so menu.childNodes() has 7 entries while menu.children() has only the 3 elements.

CSS selectors

Usually it's easier to query with CSS selectors than to walk the tree. select() returns all matches as Elements and selectFirst() returns Element?:

import org.jsoup.Jsoup

val html = """
<div class="post featured" data-id="17" data-author="ann">
  <h2><a href="/posts/kotlin-2-2">What's new in Kotlin 2.2</a></h2>
  <p class="meta">by <span class="author">Ann</span> &middot; <time datetime="2026-05-01">May 1</time></p>
  <p>Guard conditions in <code>when</code> expressions.</p>
  <a href="https://kotlinlang.org/docs/whatsnew22.html">Release notes</a>
  <a href="/files/slides.pdf">Slides (PDF)</a>
</div>
<div class="post" data-id="18" data-author="bob">
  <h2><a href="/posts/jsoup-tips">Jsoup tips</a></h2>
  <p class="meta">by <span class="author">Bob</span> &middot; <time datetime="2026-06-12">June 12</time></p>
  <p>Select elements with CSS.</p>
</div>
"""

fun main() {
    val doc = Jsoup.parse(html, "https://blog.example.com/")

    println(doc.select("div.post").size)                        // 2
    println(doc.select("div.post.featured h2").text())          // What's new in Kotlin 2.2
    println(doc.select("span.author").eachText())               // [Ann, Bob]
    println(doc.select("time[datetime]").eachAttr("datetime"))  // [2026-05-01, 2026-06-12]
    println(doc.select("a[href^=https]").eachAttr("href"))      // [https://kotlinlang.org/docs/whatsnew22.html]
    println(doc.select("a[href$=.pdf]").text())                 // Slides (PDF)
    println(doc.select("div[data-author=bob] h2 a").attr("abs:href"))
    // https://blog.example.com/posts/jsoup-tips
    println(doc.select("div.post:has(a[href$=.pdf])").attr("data-id"))  // 17
    println(doc.select("p:contains(css)").text())               // Select elements with CSS.
    println(doc.select("div.post > p:not(.meta)").size)         // 2
    println(doc.select("h2 a:matches([0-9]+[.][0-9]+)").text()) // What's new in Kotlin 2.2
}

The selectors you'll use most:

Selector Matches
tag, #id, .class by tag name, id, class
div.a.b <div> with both classes
a b, a > b descendant, direct child
a + b, a ~ b next sibling, any later sibling
[attr], [attr=v] has attribute, attribute equals
[attr^=v], [attr$=v], [attr*=v] starts with, ends with, contains
[attr~=regex] attribute value matches regex
:has(sel) element containing a match for sel
:not(sel) element not matching sel
:contains(text) text (including descendants) contains text, case-insensitive
:containsOwn(text) the element's own text contains text
:matches(regex), :matchesOwn(regex) text matches regex
:first-child, :last-child, :nth-child(2n+1) structural pseudo-classes
:eq(n), :lt(n), :gt(n) sibling index (0-based)
h1, h2, h3 any of the selectors, returned in document order

Calling select() on an Element searches only inside that element, so you can select the repeated blocks first and then query each block separately.

If an element must exist, use expectFirst(). It throws an exception with a clear message instead of returning null:

val title = doc.expectFirst("div.post h2").text()

Extracting text, HTML and attributes

import org.jsoup.Jsoup

fun main() {
    val doc = Jsoup.parse("""
        <p id="p">Hello <b>there</b>   now!</p>
        <pre id="code">fun main() {
    println("hi")
}</pre>
        <a id="a" href="../docs/" class="btn primary" data-track="nav">Docs</a>
    """, "https://example.com/blog/post")

    val p = doc.expectFirst("#p")
    println(p.text())       // Hello there now!
    println(p.ownText())    // Hello now!
    println(p.html())       // Hello <b>there</b> now!
    println(p.outerHtml())  // <p id="p">Hello <b>there</b> now!</p>

    // text() normalizes whitespace, wholeText() preserves it
    println(doc.expectFirst("#code").wholeText())

    val a = doc.expectFirst("#a")
    println(a.attr("href"))         // ../docs/
    println(a.absUrl("href"))       // https://example.com/docs/
    println(a.attr("missing"))      // "" (empty string, never null)
    println(a.hasAttr("missing"))   // false
    println(a.classNames())         // [btn, primary]
    println(a.hasClass("primary"))  // true
    println(a.dataset())            // {track=nav}
}

Things to remember:

Kotlin extensions for cleaner extraction

jsoup returns "" for missing attributes, while idiomatic Kotlin uses null. A few small extension functions make extraction code clearer:

import org.jsoup.nodes.Element

operator fun Element.get(attr: String): String? =
    if (hasAttr(attr)) attr(attr) else null

fun Element.textOf(css: String): String? =
    selectFirst(css)?.text()?.takeIf { it.isNotBlank() }

fun Element.decimalOf(css: String): Double? =
    textOf(css)?.filter { it.isDigit() || it == '.' }?.toDoubleOrNull()

With those extensions, mapping repeated blocks to data classes is short:

import org.jsoup.Jsoup

data class Product(
    val sku: String,
    val name: String,
    val price: Double?,
    val badge: String?,
    val url: String,
)

fun main() {
    val html = """
        <div class="card" data-sku="KB-1"><h3>Keyboard</h3><span class="price">$1,299.00</span>
          <span class="badge">New</span><a href="/p/kb-1">View</a></div>
        <div class="card" data-sku="MS-2"><h3>Mouse</h3><span class="price">$49.50</span>
          <a href="/p/ms-2">View</a></div>
        <div class="card"><h3>Broken card without sku</h3></div>
    """
    val doc = Jsoup.parse(html, "https://shop.example.com/")

    val products = doc.select("div.card").mapNotNull { card ->
        Product(
            sku = card["data-sku"] ?: return@mapNotNull null,
            name = card.textOf("h3") ?: return@mapNotNull null,
            price = card.decimalOf(".price"),
            badge = card.textOf(".badge"),
            url = card.selectFirst("a[href]")?.absUrl("href").orEmpty(),
        )
    }
    products.forEach(::println)
}

Output:

Product(sku=KB-1, name=Keyboard, price=1299.0, badge=New, url=https://shop.example.com/p/kb-1)
Product(sku=MS-2, name=Mouse, price=49.5, badge=null, url=https://shop.example.com/p/ms-2)

return@mapNotNull null skips blocks that are missing required fields, and optional fields simply end up as null.

Parsing tables

A common task is turning an HTML table into records. Read the header cells first, then zip each row with them:

import org.jsoup.Jsoup

data class Language(val name: String, val year: Int, val creator: String)

fun main() {
    val doc = Jsoup.parse("""
        <table id="langs">
          <thead><tr><th>Language</th><th>Year</th><th>Creator</th></tr></thead>
          <tbody>
            <tr><td>Kotlin</td><td>2011</td><td>JetBrains</td></tr>
            <tr><td>Go</td><td>2009</td><td>Google</td></tr>
            <tr><td>Rust</td><td>2010</td><td>Mozilla</td></tr>
          </tbody>
        </table>
    """)

    val table = doc.expectFirst("table#langs")
    val headers = table.select("thead th").eachText()

    val rows: List<Map<String, String>> = table.select("tbody tr").map { tr ->
        headers.zip(tr.select("td").eachText()).toMap()
    }
    println(rows.first())  // {Language=Kotlin, Year=2011, Creator=JetBrains}

    val langs = rows.map { Language(it.getValue("Language"), it.getValue("Year").toInt(), it.getValue("Creator")) }
        .sortedBy { it.year }
    langs.forEach { println("${it.year} ${it.name} (${it.creator})") }
}

Output:

{Language=Kotlin, Year=2011, Creator=JetBrains}
2009 Go (Google)
2010 Rust (Mozilla)
2011 Kotlin (JetBrains)

Looking up columns by header name instead of by position means the code keeps working when the site reorders its columns. If the table has no <thead>, use tr:first-child th or skip the first row with drop(1). Watch out for colspan and rowspan: rows that use them have fewer cells than there are headers.

Traversing the whole tree

To visit every node, for example to build an outline or collect text in a custom way, use traverse(). The lambda gets each node and its depth relative to the starting element:

import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.nodes.TextNode

fun main() {
    val doc = Jsoup.parse("<div><p>Hi <b>you</b></p><ul><li>one</li></ul></div>")

    doc.body().traverse { node, depth ->
        val indent = "  ".repeat(depth)
        when (node) {
            is Element -> println("$indent<${node.tagName()}>")
            is TextNode -> if (!node.isBlank) println("$indent\"${node.text()}\"")
        }
    }
}

Output:

<body>
  <div>
    <p>
      "Hi "
      <b>
        "you"
    <ul>
      <li>
        "one"

For most tasks a selector is simpler. For example, a table of contents is just doc.select("h1, h2, h3"), which returns the headings in document order:

val toc = doc.select("h1, h2, h3").map { h ->
    val level = h.tagName().substring(1).toInt()
    "  ".repeat(level - 1) + "- " + h.text()
}

Modifying a document

The DOM is mutable. You can change attributes, add or remove elements, and then serialize the result:

import org.jsoup.Jsoup

fun main() {
    val doc = Jsoup.parse(
        """<div id="nav"><a href="/a">A</a><a href="https://ext.com">Ext</a><script>track()</script></div>""",
        "https://example.com/",
    )
    doc.outputSettings().prettyPrint(false)

    doc.select("script").remove()

    for (a in doc.select("a[href]")) {
        a.attr("href", a.absUrl("href"))
        if (!a.attr("href").startsWith("https://example.com/")) {
            a.attr("rel", "noopener").attr("target", "_blank")
        }
    }

    doc.expectFirst("#nav").appendElement("a").attr("href", "/c").text("C")

    println(doc.expectFirst("#nav").outerHtml())
}

Output:

<div id="nav"><a href="https://example.com/a">A</a><a href="https://ext.com" rel="noopener" target="_blank">Ext</a><a href="/c">C</a></div>

Other useful mutators:

By default outerHtml() and doc.html() pretty-print, which adds newlines and indentation. Use prettyPrint(false) when you need output that stays close to the input, for example when you rewrite a template and write it back to disk.

Sanitizing untrusted HTML

If you display HTML submitted by users (comments, rich-text editor output) you have to strip scripts, event handlers and javascript: URLs, otherwise you open the door to cross-site scripting. Jsoup.clean() parses the input and keeps only the tags and attributes allowed by a Safelist:

import org.jsoup.Jsoup
import org.jsoup.safety.Safelist

fun main() {
    val dirty = """<p>Hi <a href="http://x.com/" onclick="steal()">there</a>""" +
        """<script>alert(1)</script><img src="a.png"></p>"""

    println(Jsoup.clean(dirty, Safelist.basic()))
    // <p>Hi <a href="http://x.com/" rel="nofollow">there</a></p>

    println(Jsoup.clean(dirty, Safelist.none()))
    // Hi there

    println(Jsoup.isValid("<p>ok <b>fine</b></p>", Safelist.basic()))  // true
    println(Jsoup.isValid(dirty, Safelist.basic()))                    // false

    val custom = Safelist.basic()
        .addTags("h2", "h3")
        .addAttributes("a", "title")
        .addProtocols("img", "src", "https")
        .addTags("img").addAttributes("img", "src", "alt")
    println(Jsoup.clean("""<h2 style="color:red">Title</h2><img src="https://i.example/x.png" alt="x">""", custom))
}

The built-in safelists, from strictest to most permissive:

By default relative links are removed, because they can't be checked against the allowed protocols. To keep them, call preserveRelativeLinks(true) on the safelist and pass a base URI with Jsoup.clean(html, baseUri, safelist).

Sanitize when you store the input or when you render it, but don't try to do it yourself with regular expressions.

Entities

Parser.unescapeEntities() decodes entities in a plain string, and Entities.escape() encodes text for safe insertion into HTML:

import org.jsoup.nodes.Entities
import org.jsoup.parser.Parser

fun main() {
    println(Parser.unescapeEntities("Fish &amp; Chips &copy; 2026", false))  // Fish & Chips © 2026
    println(Entities.escape("Tom & Jerry <3"))                              // Tom &amp; Jerry &lt;3
}

Parsing XML

jsoup also includes an XML parser that keeps tag names exactly as written and doesn't apply HTML rules. This matters for formats like RSS: in HTML <link> is a void element with no content, so the HTML parser would lose the link text.

import org.jsoup.Jsoup
import org.jsoup.parser.Parser

data class FeedItem(val title: String, val link: String, val author: String?)

fun main() {
    val xml = """
        <?xml version="1.0" encoding="UTF-8"?>
        <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
          <channel>
            <title>Kotlin News</title>
            <item><title>Kotlin 2.2 released</title><link>https://kotl.in/22</link><dc:creator>JetBrains</dc:creator></item>
            <item><title>Jsoup tips</title><link>https://example.com/jsoup</link></item>
          </channel>
        </rss>
    """.trimIndent()

    val doc = Jsoup.parse(xml, "", Parser.xmlParser())
    println(doc.expectFirst("channel > title").text())  // Kotlin News

    val items = doc.select("item").map { item ->
        FeedItem(
            title = item.expectFirst("title").text(),
            link = item.expectFirst("link").text(),
            author = item.selectFirst("dc|creator")?.text(),  // ns|tag selects a namespaced tag
        )
    }
    items.forEach(::println)
}

Output:

Kotlin News
FeedItem(title=Kotlin 2.2 released, link=https://kotl.in/22, author=JetBrains)
FeedItem(title=Jsoup tips, link=https://example.com/jsoup, author=null)

For strict XML processing (schemas, namespaces done properly, very large files), use the JDK's javax.xml APIs or a dedicated library instead.

Alternatives

Common pitfalls

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents