As a prerequisite, Chrome is already installed.
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 to start faster than normal startexample.py
#Service startup
service = Service(executable_path='/usr/local/bin/chromedriver')
service.start()
#Connect to Chrome
driver = webdriver.Remote(service.service_url, desired_capabilities=options.to_capabilities())
All you have to do now is run Slenium as usual.
The following error may occur in the CUI environment
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)
It happened when I ran the sendKeys () method.
This can be avoided by entering characters etc. with JavaScript instead of sendKeys ().
If you get other errors, you can probably avoid them by running JavaScript.
example.py
# driver.get_element_by_css_selector('hoge').sendKeys('fuga')Raises an exception
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()I get an exception when I run 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()
Recommended Posts