Created
March 2, 2021 12:44
-
-
Save marquesds/facfdf8c7e1b9c94bec4f362f7abd142 to your computer and use it in GitHub Desktop.
A simple web scraping with Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Crawler.kt | |
import kotlinx.coroutines.* | |
import org.json.JSONObject | |
import org.jsoup.Jsoup | |
import org.jsoup.nodes.Document | |
import org.jsoup.nodes.Element | |
import org.jsoup.select.Elements | |
class Crawler { | |
suspend fun pipeline(urls: List<String>, selector: String): List<Elements> = coroutineScope { | |
retrieveAllHtmlDocumentAsync(urls).awaitAll().map { parse(it, selector) } | |
} | |
private fun parse(document: Document, selector: String): Elements { | |
return document.select(selector) | |
} | |
private suspend fun retrieveAllHtmlDocumentAsync(urls: List<String>): List<Deferred<Document>> = coroutineScope { | |
urls.map { url -> | |
async { | |
Jsoup.parse(khttp.get(url).text) | |
} | |
} | |
} | |
private fun toJson(element: Element): JSONObject { | |
return JSONObject(element) | |
} | |
} | |
// Skrotlin.kt - main | |
import kotlin.system.measureTimeMillis | |
suspend fun main(args: Array<String>) { | |
val vanDelay = "http://slowwly.robertomurray.co.uk/delay/3000/url" | |
val totalTime = measureTimeMillis { | |
val crawler = Crawler() | |
val result = crawler.pipeline(listOf("$vanDelay/https://http.cat", | |
"$vanDelay/https://httpstatusdogs.com/", | |
"$vanDelay/https://gympass.com", | |
"$vanDelay/https://google.com", | |
"$vanDelay/https://stackoverflow.com"), "div") | |
println(result) | |
println(result.size) | |
} | |
println("total time: $totalTime") | |
} |
Making parse async:
import kotlinx.coroutines.*
import org.json.JSONObject
import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.select.Elements
class Crawler {
suspend fun pipeline(urls: List<String>, selector: String): List<Elements> = coroutineScope {
retrieveAllHtmlDocumentAsync(urls, selector).awaitAll()
}
private suspend fun retrieveAllHtmlDocumentAsync(urls: List<String>, selector: String): List<Deferred<Elements>> = coroutineScope {
urls.map { url ->
async {
parse(Jsoup.parse(khttp.get(url).text), selector)
}
}
}
private fun parse(document: Document, selector: String): Elements {
return document.select(selector)
}
private fun toJson(element: Element): JSONObject {
return JSONObject(element)
}
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maven dependencies: