How do I use Selenium Webdriver on headless Chrome?
I found this blog post useful for setting up headless chrome with selenium in ruby
require "selenium-webdriver"# configure the driver to run in headless modeoptions = Selenium::WebDriver::Chrome::Options.newoptions.add_argument('--headless')driver = Selenium::WebDriver.for :chrome, options: optionsdriver.navigate.to "https://www.google.com"# resize the window and take a screenshotdriver.manage.window.resize_to(800, 800)driver.save_screenshot "screenshot.png"
Managed to work through this in the end via various docs, blog posts and gists.
caps = Selenium::WebDriver::Remote::Capabilities.chrome("desiredCapabilities" => {"takesScreenshot" => true}, "chromeOptions" => {"binary" => "/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary"})driver = Selenium::WebDriver.for :chrome, desired_capabilities: caps, switches: %w[--headless --no-sandbox --disable-gpu --remote-debugin-port=9222 --screen-size=1200x800]
You need to use a very recent version of Chrome (I'm using Canary) and tell Selenium the path to the binary. You also need to set the desired capabilities for 'takesScreenshot' to true.
I've written a blog post about how to do it. Summing up:
1) Make sure you have Chrome version 57+ on Linux, 59+ on macOS or 60+ on Windows;
2) Add/update the gem selenium-webdriver
;
3) Make sure you’re using ChromeDriver version 2.30 or higher;
4) Add the following driver to your spec_helper.rb
or rails_helper.rb
:
Capybara.register_driver :chrome do |app| Capybara::Selenium::Driver.new app, browser: :chrome, options: Selenium::WebDriver::Chrome::Options.new(args: %w[headless disable-gpu])endCapybara.javascript_driver = :chrome