首页 > 解决方案 > 如何使用 Selenium 在 Ruby Capybara 中启用 ChromeDriver 日志记录?

问题描述

我试图在 ruby​​ Capybara 中注册 Selenium chrome 驱动程序。但不幸的是,我没有找到任何有关启用日志记录的信息。我使用了添加了 perfLoggingPrefs: {enableNetwork: true} 的选项,并遇到了我应该启用日志记录的问题。有谁知道如何在 Ruby/Capybara 中启用 ChromeDriver 的日志记录?所以这是我现在的代码:

    Capybara.register_driver(:selenium_mobile) do |app|
     options = Selenium::WebDriver::Chrome::Options.new
     options.add_emulation(device_name: 'iPhone X')
     options.add_option(:perfLoggingPrefs, {enableNetwork: true})
     p "Default Selenium driver is used"
     cps = Selenium::WebDriver::Remote::Capabilities.chrome(
       loggingPrefs: {browser: 'ALL'},
       perfLoggingPrefs: {enableNetwork: true})

      Capybara::Selenium::Driver.new(app, browser: :chrome, 
    desired_capabilities: cps, options: 
       options)
      end
    end

另外,我尝试输入命令行参数,例如

      options.add_argument('verbose')
      options.add_argument('log-path=./tmp/chromedriver.log')

无论如何我得到问题:

Selenium::WebDriver::Error::InvalidArgumentError:无效参数:“firstMatch”的条目 0 因无效参数无效:指定了 perfLoggingPrefs,但未启用性能日志记录

我已经读过可以启用 ChromeDriver 日志记录,LoggingPreferences但我找不到任何关于 Ruby 的提及。

有谁知道在注册 Selenium 驱动程序时如何在 Ruby/Capybara 中启用 ChromeDriver 的日志记录?

标签: rubyseleniumselenium-webdriverselenium-chromedrivercapybara

解决方案


您已经在功能中添加了日志记录首选项。

此外,您可以创建一种方法来将日志存储在您需要的任何位置。这是我用来在您需要的特定文件夹上写入日志的方法。您可以在后挂钩中调用此方法。此外,如果您想在任何 CI/CD 应用程序中查看,您可以将其存储为工件

 def capture_browser_logs
  errors = Capybara.page.driver.browser.manage.logs.get(:browser)
                   .select { |e| e.level == "SEVERE" && e.message.present? }
                   .map(&:message)
                   .to_a
  return if errors.none?
  message = errors.join("\n\n")

  # writes console errors to a log file
  log_file_path = Rails.root.join("tmp", "smoke_tests", "console_logs", "js_errors.log")
  FileUtils.mkdir_p(log_file_path.dirname) unless File.directory?(log_file_path.dirname)

  logging_destination = if ENV["RAILS_LOG_TO_STDOUT"].present? && ENV["RAILS_LOG_TO_STDOUT"].to_s == "true"
                          STDOUT
                        else
                          log_file_path
                        end

  logger = Logger.new(logging_destination)
  logger.error(message)
end

推荐阅读