Web scraping

suggest change

In Kotlin, web scraping involves downloading HTML over HTTP and parsing its Document Object Model (DOM) to extract structured data. Because Kotlin has seamless interoperability with the Java ecosystem, Jsoup is the most widely adopted scraping library. Kotlin's language features—such as data classes, extension functions, null-safety, and coroutines—make scraping code concise and robust.

Setting Up Jsoup

Add Jsoup to your build.gradle.kts:

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

Basic HTML Scraping and Modeling with Data Classes

Combine Jsoup with a Kotlin data class to extract structured domain models cleanly:

import org.jsoup.Jsoup

data class Article(
    val title: String,
    val link: String,
    val score: Int
)

fun scrapeHackerNews(): List<Article> {
    val doc = Jsoup.connect("https://news.ycombinator.com/")
        .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64)")
        .timeout(10_000)
        .get()

    val rows = doc.select("tr.athing")

    return rows.mapNotNull { row ->
        val titleElement = row.selectFirst("span.titleline > a") ?: return@mapNotNull null
        val subtext = row.nextElementSibling()?.selectFirst("td.subtext")

        val title = titleElement.text()
        val link = titleElement.attr("abs:href")
        val scoreText = subtext?.selectFirst("span.score")?.text() ?: "0 points"
        val score = scoreText.filter { it.isDigit() }.toIntOrNull() ?: 0

        Article(title, link, score)
    }
}

fun main() {
    val articles = scrapeHackerNews()
    articles.take(5).forEach {
        println("[+${it.score}] ${it.title} (${it.link})")
    }
}

Leveraging Kotlin Null-Safety with Selectors

Web markup frequently changes or omits optional elements. Kotlin's safe call operator (?.) and Elvis operator (?:) prevent NullPointerExceptions when querying the DOM:

import org.jsoup.nodes.Element

data class Product(val id: String, val name: String, val price: Double, val badge: String)

fun parseProduct(card: Element): Product {
    val id = card.attr("data-product-id")
    val name = card.selectFirst("h2.title")?.text().orEmpty()

    val priceRaw = card.selectFirst("span.price")?.text() ?: "0.0"
    val price = priceRaw.replace("$", "").toDoubleOrNull() ?: 0.0

    // Elvis operator provides default when optional badge is missing
    val badge = card.selectFirst("span.badge")?.text() ?: "Standard"

    return Product(id, name, price, badge)
}

Concurrent Scraping with Kotlin Coroutines

When scraping hundreds of pages, performing requests sequentially is slow. Use Kotlin Coroutines and Dispatchers.IO to fetch multiple pages concurrently:

import kotlinx.coroutines.*
import org.jsoup.Jsoup

suspend fun fetchPageTitle(url: String): String = withContext(Dispatchers.IO) {
    try {
        val doc = Jsoup.connect(url).timeout(5_000).get()
        doc.title()
    } catch (e: Exception) {
        "Failed: ${e.message}"
    }
}

suspend fun scrapeUrlsConcurrently(urls: List<String>): Map<String, String> = coroutineScope {
    urls.map { url ->
        async { url to fetchPageTitle(url) }
    }.awaitAll().toMap()
}

Best Practices

Feedback about page:

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



Table Of Contents