Kotlin中使用Selenium 自动签到《ruike1》

1、下载驱动(使用edge)

url:https://www.selenium.dev/ 下载对应浏览器驱动,放在浏览器根目录
例如:C:\Program Files (x86)\Microsoft\Edge\Application\msedgedriver.exe

2、新建项目(这里使用ktor)

image

3、添加依赖

implementation("org.seleniumhq.selenium:selenium-java:4.35.0")
implementation("org.seleniumhq.selenium:selenium-edge-driver:4.35.0")

image

4、主要代码

package com.selenium
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import org.openqa.selenium.edge.EdgeDriver
import org.openqa.selenium.edge.EdgeOptions
import org.openqa.selenium.support.ui.WebDriverWait
import java.time.Duration


fun Application.configureRouting() {
    routing {
        get("/login"){
            val result = withContext(Dispatchers.IO){
                val service = WebAutomationService()
                service.performCheckin("username", "password#")
            }
            //答应当前时间和结果
            println("签到时间: ${System.currentTimeMillis()} 结果: $result")
            call.respondText(result)
        }
    }
}
// 使用扩展函数,简化代码
fun EdgeDriver.lazyLoad(by: By): WebElement {
    return WebDriverWait(this, Duration.ofMillis(500)).until {
        this.findElement(by)
    }
}
class WebAutomationService {
    suspend fun performCheckin(username: String, password: String): String {
        return seleniumOperation { driver ->
            try {
                // 访问网站
                driver.get("https://www.ruike1.com/")
                // 登录操作
                driver.lazyLoad(By.id("ls_username")).sendKeys(username)
                driver.lazyLoad(By.id("ls_password")).sendKeys(password)
                driver.lazyLoad(By.xpath("//*[@id=\"lsform\"]/div/div/table/tbody/tr[2]/td[3]/button"))
                    .click()
                // 签到操作
                driver.lazyLoad(By.id("fx_checkin_b")).click()
                "签到成功: ${driver.title}"
            }catch (e: Exception){
                "签到失败: ${e.message}"
            }


        }
    }

    private suspend fun <T> seleniumOperation(block: (EdgeDriver) -> T): T {
        return withContext(Dispatchers.IO) {
            val options = EdgeOptions().apply {
                // 启用无头模式,在锁屏时更稳定
                addArguments("--headless")
                addArguments("--disable-gpu")
                addArguments("--no-sandbox")
                addArguments("--disable-dev-shm-usage")
            }
            val driver = EdgeDriver(options)
            driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))
            try {
                block(driver)
            } finally {
                driver.quit()
            }
        }
    }
}
posted @ 2025-08-30 11:45  一个小笨蛋  阅读(10)  评论(0)    收藏  举报