LoginSignup
1
1

More than 3 years have passed since last update.

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

Posted at

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系で動くように直します。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1