LoginSignup
0
0

More than 1 year has passed since last update.

Selenium(Capybara)+Firefox+Rubyでconsole.logを取得する

Last updated at Posted at 2022-07-04

このページについて

Firefox + Selenium(Capybara) で console.log に出力される値を取得する方法について、苦戦したので備忘録です。

環境

  • Ruby 2.6
  • Capybara 3.32.1
  • Firefox 2022/7/5 時点で最新のもの
  • Geckodriver 2022/7/5 時点で最新のもの

やりたいこと

console.log に出力される値を Selenium で取得し、ログに出力したい。

Chrome の場合は driver.manage.logs.get で簡単に取得できますが、Geckodriver ではこの方法は現時点では使えません。
以下 issue に代替案が書かれていますので、こちらを参考にします。
https://github.com/mozilla/geckodriver/issues/284

コード

Capybara の設定に devtools.console.stdout.content を追加します。

Capybara.register_driver :selenium_headless do |app|
  options = ::Selenium::WebDriver::Firefox::Options.new
  options.headless!
  options.add_preference('devtools.console.stdout.content', true)  # ここを追加
  Capybara::Selenium::Driver.new(app, browser: :firefox, options: 
  options)
end

Geckodriver 側の設定は以上です。
さらに Selenium の logger.leveldebug にします。

Selenium::WebDriver.logger.level = :debug
Selenium::WebDriver.logger.output = 'selenium.log'

これで console.log の値が selenium.log へ出力されるようになります。

Selenium のログレベルが debug でないと、 Selenium が Geckodriver のログを抑制してしまうそうです。
https://github.com/SeleniumHQ/selenium/issues/7140#issuecomment-486993770
debug レベルだとログの出力量が膨大になってしまいますが仕方ありません・・・

ログのサンプル

console 関連のログは以下のように出力されます。

console.warn: SearchSettings: "get: No settings file exists, new profile?" (new NotFoundError("Could not open the file at /tmp/hoge/search.json.mozlz4", (void 0)))
console.log: "JQMIGRATE: Migrate is installed with logging active, version 3.4.0"
0
0
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
0
0