LoginSignup
30
37

More than 5 years have passed since last update.

CUI 環境で Selenium と Headless Chrome を使用する場合の Tips

Last updated at Posted at 2017-06-09

CUI 環境で Selenium と Headless Chrome を使用する

環境

  • Ubuntu Server 16.04.02
  • Python 3.5
  • Selenium 3
  • Chrome 59

使用方法

前提として Chrome がすでにインストール済み。

Headless Chrome を使用するために、オプションを指定します

example.py
options = webdriver.ChromeOptions()
options.binary_location = '/usr/bin/google-chrome'
options.add_argument('--headless')
options.add_argument('--disable-gpu')
options.add_argument('--no-sandbox')
options.add_argument('--window-size=1200x600')

普通に起動するより高速に起動させるためにServiceを起動する

example.py
# サービスの起動
service = Service(executable_path='/usr/local/bin/chromedriver')
service.start()
# Chrome に接続
driver = webdriver.Remote(service.service_url, desired_capabilities=options.to_capabilities())

あとはいつもどおり、Slenium を実行するだけです。

Selenium のメソッドを使用するとエラーが発生する場合

CUI 環境では以下のエラーが発生する場合があります

error.log
selenium.common.exceptions.WebDriverException: Message: unknown error: an X display is required for keycode conversions, consider using Xvfb
  (Session info: headless chrome=59.0.3071.86)
  (Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 4.8.0-49-generic x86_64)

私は、sendKeys() メソッドを実行した際に発生しました。
これは、sendKeys() ではなく JavaScript で文字の入力等を行うことで回避できます。
この他のエラーが発生した場合も JavaScript を実行することで回避可能だと思われます。

例:

example.py
# driver.get_element_by_css_selector('hoge').sendKeys('fuga') は例外が発生
def _set_value_for_element(selector: str, value: str):
        return 'document.querySelector("{selector}").setAttribute("value", "{value}")'.format(selector=selector, value=value)

driver.get(url)
# sendKeys() を実行すると例外が発生するので、JSを実行する
driver.execute_script(_set_value_for_element(user_name_selector, user_name))
driver.execute_script(_set_value_for_element(user_password_selector, user_password))
driver.find_element_by_css_selector(login_button_selector).click()
30
37
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
30
37