(自分メモ)
下記と同じことをKotlin/jvmで書きたい。テスト用サーバも。
環境
- Ubuntu 22.04 on wsl2 on Windows 11
- JDK 21
Project初期化
build.gradle.kts
plugins {
kotlin("jvm") version "1.9.23"
application
}
repositories { mavenCentral() }
dependencies {
implementation("com.microsoft.playwright:playwright:1.43.0") // https://mvnrepository.com/artifact/com.microsoft.playwright/playwright
implementation("io.ktor:ktor-server-cio:2.3.10") // https://mvnrepository.com/artifact/io.ktor/ktor-server-cio
}
application {mainClass.set("MainKt")}
➜ソース
Main.kt
fun main() {
thread { testServer() }
Playwright.create().use { playwright ->
val browser = playwright.chromium().launch(BrowserType.LaunchOptions().apply { headless = false })
val page = browser.newPage()
page.navigate("http://localhost:8000/")
val text = page.getByRole(AriaRole.HEADING).textContent()
println(text)
browser.close()
}
}
val testPage = """
<!DOCTYPE html><html>
<head><title>Hello World</title></head><body>
<h1>Hello World!</h1>
</body></html>
"""
fun testServer() = embeddedServer(CIO, port = 8000) {
routing {
get("/") { call.respondText(testPage, ContentType.Text.Html) }
}
}.start(wait = false)
Build/Run
gradlew run
参考