Chrome用WebDriverの仕組みが変わってた

2024/05/02 20:48

※ 商品のリンクをクリックして何かを購入すると私に少額の報酬が入ることがあります【広告表示】

tl;dr

WebDriver

seleniumからChromeを動作させるためにはChromeのWebDriverをインストールする必要がある。

Chromeのバージョン114以降、以前のロジックを使ってWebDriverをインストールすると、WebDriverの114がインストールされて、バージョンが合わないというエラーで落ちる。

  selenium.common.exceptions.SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 114
  Current browser version is 124.0.6367.78 with binary path /usr/bin/google-chrome

webdriver_manager? selenium manager?

WebDriverが入らんなと彷徨っていると、webdriver_managerやselenium managerといった名前も出てくる。このselenium managerというものがseleniumに標準で搭載されたため、WebDriverを別途インストールする必要がなくなった。逆に変なバージョンのWebDriverが入っていると動作しないのでインストールしないのが正解。

Selenium 4.6以降は now with batteries included! ということで、 webdriver.Chrome() とした時点でインストールされていなかったらWebDriverがインストールされる。

どこにインストールされる?

Docker上のlinuxで実行したら /root/.cache/selenium/chromedriver/linux64/124.0.6367.78/chromedriver にインストールされました(124.0.6367.78はバージョン)。

M1などApple SiliconのDockerでChromeが起動しないんだけど

ChromeはApple Siliconのmac上のDockerで動かすには設定が必要でした。

  selenium.common.exceptions.WebDriverException: Message: disconnected: Unable to receive message from renderer
  (failed to check if window was closed: disconnected: not connected to DevTools)
  (Session info: chrome=124.0.6367.78)

Docker Deskopの設定から、 Use Rosetta for x86_64/amd64 emulation on Apple Silicon にチェックを入れると動きます。

Docker Desktop → 歯車 → General → Use Rosetta for x86/amd64 emulation on Apple Silicon

Chrome WebDriver/Chromeの詳細なログを出す

Chromeが起動しないエラーはいろんな原因があるらしく、エラーの原因を探るのに詳細にログが出るようにしました。

  from selenium import webdriver

  chrome_options = webdriver.ChromeOptions()
  chrome_options.add_argument('--no-sandbox')
  chrome_options.add_argument('--headless=new')

  import logging
  import subprocess

  logging.basicConfig(level=logging.WARN)
  logging.getLogger('selenium').setLevel(logging.DEBUG)

  service = webdriver.ChromeService(service_args=['--log-level=DEBUG'], log_output=subprocess.STDOUT)
  driver = webdriver.Chrome(chrome_options, service)

詳細なログからググったらM1 macのDockerでChrome動かないという情報に辿り着けたのでした。

Prev Entry