com.blr19c.falowp.bot.system.web.Webdriver.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of falowp-bot-system Show documentation
Show all versions of falowp-bot-system Show documentation
FalowpBot system infrastructure
package com.blr19c.falowp.bot.system.web
import com.blr19c.falowp.bot.system.Log
import com.blr19c.falowp.bot.system.image.encodeToBase64String
import com.microsoft.playwright.*
import com.microsoft.playwright.options.LoadState
import com.microsoft.playwright.options.ViewportSize
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* Webdriver截图使用
*/
object Webdriver : Log {
internal fun configure() {
log().info("初始化Webdriver")
playwright
log().info("初始化Webdriver完成")
}
}
private val playwright by lazy {
Playwright.create()
}
/**
* 存在这个元素的情况下执行
*/
fun Page.existsToExecute(
selector: String,
onlyOne: Boolean = true,
block: ElementHandle.() -> T
): List {
val allElementHandle = this.querySelectorAll(selector)
if (allElementHandle.isNullOrEmpty()) return emptyList()
if (onlyOne) return listOf(block.invoke(allElementHandle.first()))
return allElementHandle.map { block.invoke(it) }.toList()
}
fun browser(block: Browser.() -> T): T {
val chromium = playwright.chromium()
return chromium.launch().use { block.invoke(it) }
}
fun commonWebdriverContext(block: BrowserContext.() -> T): T {
return browser {
val browserContext = this.newContext(
Browser.NewContextOptions()
.setViewportSize(ViewportSize(1920, 1080))
.setUserAgent(commonUserAgent())
.setIsMobile(false)
)
browserContext.use { block.invoke(it) }
}
}
suspend fun htmlToImageBase64(html: String, querySelector: String = "body"): String {
return withContext(Dispatchers.IO) {
commonWebdriverContext {
this.newPage().use { page ->
page.setContent(html)
page.waitForLoadState(LoadState.NETWORKIDLE)
page.querySelector(querySelector).screenshot().encodeToBase64String()
}
}
}
}