SeleniumJava+ChromeDriverでconsole.log()の出力値を取得する


KotlinでSeleniumを使ってみようと思ったら、console.log()の内容をとるのにちょっと苦労したのでメモ。

環境

  • MacOS
    • 1.14
  • Kotlin
    • 1.3.21
  • Selenium-Java
    • 2.53.1
  • ChromeDriver
    • 75.0.3770.8

build.gradle

plugins {
    id 'org.jetbrains.kotlin.jvm' version '1.3.21'
}

repositories {
    mavenCentral()
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
    //implementation "org.seleniumhq.selenium:selenium-java:3.141.59"
    implementation "org.seleniumhq.selenium:selenium-java:2.53.1"
}

compileKotlin {
    kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
    kotlinOptions.jvmTarget = "1.8"
}

コード

import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.chrome.ChromeDriverService
import org.openqa.selenium.chrome.ChromeOptions
import java.util.logging.Level
import org.openqa.selenium.remote.CapabilityType
import org.openqa.selenium.logging.LogType
import org.openqa.selenium.logging.LoggingPreferences
import org.openqa.selenium.remote.DesiredCapabilities


fun main(args: Array<String>) {
    val capabilities = DesiredCapabilities.chrome()
    val logPreference = LoggingPreferences()
    val options = ChromeOptions()

    // ログレベルを設定
    logPreference.enable(LogType.BROWSER, Level.ALL)
    capabilities.setCapability(CapabilityType.LOGGING_PREFS, logPreference)

    // ヘッドレスモード
    options.addArguments("--headless")
    capabilities.setCapability(ChromeOptions.CAPABILITY, options)

    val driver = ChromeDriver(capabilities)

    driver.get("https://***")

    driver.executeScript("console.log('hoge');")
    val logs = driver.manage().logs().get(LogType.BROWSER)

    logs.forEach { logEntry ->
        println(logEntry)
    }

    driver.quit()
}

ポイント

driver.setLogLevel(Level.ALL)じゃだめ、でLoggingProferenceオブジェクトを渡してやらないとダメだった。

あとSelenium-Javaの最新版は3.x系なんですが、3系だとどうもうまく行かなかったので時間があるときに原因を調べて3系で動くように直します。