LoginSignup
21
17

More than 5 years have passed since last update.

Headless Chromeでにっちもさっちもいかないとき

Posted at

Selenium + Headless Chromeでクローラを実装したけど途中で落ちてしまって原因もわからないとき、期待した結果が取得できないときの対策。

ログを出す

出力できるログは全て取る。

# Seleniumのデバッグログ (情報は少ない)
Selenium::WebDriver.logger.level = :debug
Selenium::WebDriver.logger.output = 'selenium.log'

# Chromeのログ (UserProfileに下に作成される。Linuxだと /tmp/.org.chromium.Chromium.AAAAA あたり) 
options = Selenium::WebDriver::Chrome::Options.new({
  args: ['log-level=0', 'enable-logging'],
})
# chromedriverのログ (find_element の実行結果とか全て記録されるので便利)
@driver = Selenium::WebDriver.for(:chrome, options: options, driver_opts: {
  log_path: 'chromedrive.log',
})

スクリーンショットを取る

エラーが発生したときの画面の状態をあとから確認する。

def save_screenshot(path)
  @driver.save_screenshot(path)
end

ソースを保存する

エラーが発生したときのソースをあとから確認する。

def dump_source
  filename = Digest::MD5.hexdigest(@driver.current_url)
  png_path = './log/%s.png' % filename
  html_path = './log/%s.html' % filename
  save_screenshot(png_path) # スクリーンショットとHTMLを同じファイル名にしておく
  File.open html_path, "w" do |writer|
    writer.puts @driver.current_url # 一緒にURLも出力しておくと便利
    writer.puts @driver.page_source
  end
end

ウインドウサイズを大きくする

ウインドウサイズが小さいとHTMLが崩れたりDOM要素が重なったりして意図しない結果になることがある。

options = Selenium::WebDriver::Chrome::Options.new({
  args: ['headless', 'start-maximized', 'window-size=1920,1080'],
})

日本語フォントを入れる

日本語フォントをインストールしておかないと文字化けする。たまにエラーで落ちたりする。

$ sudo yum install -y google-chrome-stable libOSMesa google-noto-cjk-fonts ipa-gothic-fonts.noarch ipa-mincho-fonts.noarch

タブの状態をログに出力する

実装が悪いとエラー発生時にタブが残ってしまい動作が不安定になるので、ちゃんとタブが閉じられているかチェックするためにログに出力しておく。

logger.info('タブ: %d' % @driver.window_handles.size)
21
17
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
21
17