Chrome for TestingでSeleniumを動かす
はじめに
ChromeDriverとChromeブラウザのバージョンの不一致でエラーが起きたことはないでしょうか。
今回はこの問題を解消するChrome for Testingを使ってSeleniumを動かす方法を紹介します。
Chrome for Testingとは
Chrome for Testingは、Googleが提供するブラウザの自動化とテストを目的として作成された特別なChromeバージョンです。通常のChromeブラウザとは異なり、テスト環境に特化した機能や設定が含まれています。
主な特徴:
- 自動更新が無効化されており、テスト環境の安定性が向上
- テスト用の特別な設定やフラグがデフォルトで有効
- ChromeDriverとの互換性が保証されており、バージョン不一致の問題を解消
詳細は公式ブログを参照してください:
https://developer.chrome.com/blog/chrome-for-testing?hl=ja
インストール
Chrome for Testingは公式サイトからダウンロードできます。また、curlコマンドを使用してインストールすることも可能です。
インストール時は、使用しているOSとアーキテクチャに適したバージョンを選択してください。
例:macOS (ARM64)の場合
curl -O https://storage.googleapis.com/chrome-for-testing-public/127.0.6533.99/mac-arm64/chrome-mac-arm64.zip
unzip chrome-mac-arm64.zip -d /Applications/
ダウンロードページ:
https://googlechromelabs.github.io/chrome-for-testing/
注意:バージョン番号は定期的に更新されるため、最新バージョンを確認してください。
実際に使ってみる
以下のPythonコードでChrome for Testingを使用してSeleniumを動かすことができます。このセットアップでは、従来のChromeDriverが不要になります。
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
# Chrome for Testingのパスを指定
chrome_binary_path = "/Applications/chrome-for-testing/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing"
# Chromeのオプションを設定
chrome_options = Options()
chrome_options.binary_location = chrome_binary_path
# Serviceオブジェクトを作成(ChromeDriverのパスは不要)
service = Service()
# WebDriverを初期化
driver = webdriver.Chrome(service=service, options=chrome_options)
# テストページを開く
driver.get("https://www.google.com")
# ブラウザを閉じる
driver.quit()
破損している場合の対処
macOSでChrome for Testingを初めて実行する際、セキュリティ警告が表示される場合があります。これを解決するには、以下のコマンドを実行してください:
xattr -cr '/Applications/chrome-for-testing/Google Chrome for Testing.app'
このコマンドは、アプリケーションに付加された拡張属性を削除し、macOSのGatekeeper機能による警告を回避します。
さいごに
Chrome for Testingを使用することで、ChromeDriverとChromeブラウザのバージョン不一致問題が解消され、より安定したテスト環境を構築できます。また、自動更新が無効化されているため、長期的なテスト実行においても一貫性が保たれます。
是非使ってみてください。