LoginSignup
15
15

More than 5 years have passed since last update.

Selenium + Headless Chromeで証明書エラーを回避する

Posted at

Google chromeを利用してWebを閲覧していると、サーバー証明書に問題があるときに証明書エラーの警告画面を出してくれる。
これはユーザーの保護のためにはとても重要な機能だ。

重要な機能なのだが、検証のために自己証明書を利用していたり、プライベートIPでアクセスしたい時など、証明書エラーを回避したい時がある。
そして、Selenium + Headless Chromeを利用していると、このエラーページが回避できない。(以下のような空白のページが返る、スクショも真っ白になる。)

<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body></body></html>

Webアプリケーションの自動テストの時など困る。

回避策としては、これはHeadless(画面無し)状態固有の制限事項なので、Virtualdisplay(Xvfb)を利用して非ヘッドレスモードで起動する方法もある。

が、Xvfbが使えない環境もあると思うので、Chromeの機能だけで実現できないかどうか調べてみた。

acceptInsecureCertsを有効にする

結論としては、ChromedriverにacceptInsecureCerts機能指定にすることで、証明書エラーを回避することができる。

以下、自己証明書を回避してサイトにアクセスし、スクショを保存するサンプルコード。

sample.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

options = Options()
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')

capabilities = DesiredCapabilities.CHROME.copy()
capabilities['acceptInsecureCerts'] = True

driver = webdriver.Chrome(chrome_options=options, desired_capabilities=capabilities)
driver.get('https://yoursite.example.com')
print(driver.title) # ページタイトルの確認
driver.save_screenshot('/tmp/screenshot.png') # スクショ保存
driver.quit()

JavaでもRubyでも、acceptInsecureCertsのcapabilitiesを有効にする点は共通だと思う。ちなみに「--ignore-certificate-error」のオプションは廃止予定なので、効かない。

Windows環境はXvfbが使えないから(WSLにすりゃ行けると思うけど)、こっちの方がいいかもしれない。

参考文献:
Provide ability to handle certificate errors in Chromedriver/Selenium for headless
https://bugs.chromium.org/p/chromium/issues/detail?id=721739#c106

15
15
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
15
15