验证码页面
验证码页面地址:https://dun.163.com/trial/jigsaw
准备工作
安装 Kotlin。
安装 Maven 或 Gradle 构建工具。
安装 ChromeDriver。
代码实现
1. 初始化项目
创建一个新的 Kotlin 项目,使用 Maven 或 Gradle 管理依赖。这里我们使用 Gradle 作为构建工具。
build.gradle.kts
kotlin
plugins {
kotlin("jvm") version "1.6.21"
}
repositories {
mavenCentral()
}
dependencies {
implementation("org.seleniumhq.selenium:selenium-java:4.1.0")
implementation("org.bytedeco:javacv-platform:1.5.6")
implementation("org.bytedeco:opencv-platform:4.5.3-1.5.6")
}
2. Kotlin 脚本(CaptchaSolver.kt)
kotlin
import org.openqa.selenium.WebDriver
import org.openqa.selenium.WebElement
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.interactions.Actions
import java.io.File
import javax.imageio.ImageIO
import org.bytedeco.opencv.opencv_core.*
import org.bytedeco.opencv.global.opencv_imgproc.*
import org.bytedeco.opencv.global.opencv_imgcodecs.*
import org.bytedeco.opencv.global.opencv_core.*
fun main() {
System.setProperty("webdriver.chrome.driver", "/path/to/chromedriver")
val driver: WebDriver = ChromeDriver()
driver.get("https://dun.163.com/trial/jigsaw")
Thread.sleep(2000)
val bgImagePath = "bgImage.png"
val tpImagePath = "tpImage.png"
val bgElement = driver.findElement(org.openqa.selenium.By.className("geetest_canvas_bg"))
val tpElement = driver.findElement(org.openqa.selenium.By.className("geetest_canvas_fullbg"))
saveElementScreenshot(driver, bgElement, bgImagePath)
saveElementScreenshot(driver, tpElement, tpImagePath)
val gap = getGap(bgImagePath, tpImagePath)
val slider = driver.findElement(org.openqa.selenium.By.className("geetest_slider_button"))
simulateDrag(driver, slider, gap.x())
Thread.sleep(5000)
driver.quit()
}
fun saveElementScreenshot(driver: WebDriver, element: WebElement, filePath: String) {
val base64Image = (driver as org.openqa.selenium.JavascriptExecutor)
.executeScript("return arguments[0].toDataURL('image/png').substring(22);", element) as String
val imageBytes = java.util.Base64.getDecoder().decode(base64Image)
File(filePath).writeBytes(imageBytes)
}
fun getGap(bgImagePath: String, tpImagePath: String): Point {
val bgImage = imread(bgImagePath)
val tpImage = imread(tpImagePath, IMREAD_GRAYSCALE)
val result = Mat()
matchTemplate(bgImage, tpImage, result, TM_CCOEFF_NORMED)
val mmr = minMaxLoc(result)
return mmr.maxLoc
}
fun simulateDrag(driver: WebDriver, element: WebElement, distance: Double) {
val action = Actions(driver)
action.clickAndHold(element).perform()
Thread.sleep(200)
val moveTrack = mutableListOf<Int>()
var currentDistance = 0.0
while (currentDistance < distance) {
val moveDistance = (5..10).random().toDouble()
moveTrack.add(moveDistance.toInt())
currentDistance += moveDistance
}
moveTrack.forEach {
action.moveByOffset(it, 0).perform()
Thread.sleep(10)
}
action.release().perform()
}
运行脚本
确保已经安装了 Gradle,并在项目根目录下运行以下命令来构建项目:
sh
gradle build
运行 Kotlin 脚本:
sh
gradle run
更多内容联系q1436423940