SeleniumJava+ChromeDriverでconsole.log()の出力値を取得する
5517 ワード
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系で動くように直します。
Author And Source
この問題について(SeleniumJava+ChromeDriverでconsole.log()の出力値を取得する), 我々は、より多くの情報をここで見つけました https://qiita.com/fisherman08/items/d0ef1a08cbd1f54683b9著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .