How do I use Selenium Webdriver on headless Chrome?

后端 未结 3 958
滥情空心
滥情空心 2021-02-20 15:51

I\'m learning to use Selenium for basic things like taking a screenshot, scraping, and testing and would like to use it with headless Chrome, which is now stable as of Chrome 59

相关标签:
3条回答
  • 2021-02-20 16:18

    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 mode
    options = Selenium::WebDriver::Chrome::Options.new
    options.add_argument('--headless')
    driver = Selenium::WebDriver.for :chrome, options: options
    
    driver.navigate.to "https://www.google.com"
    
    # resize the window and take a screenshot
    driver.manage.window.resize_to(800, 800)
    driver.save_screenshot "screenshot.png"
    
    0 讨论(0)
  • 2021-02-20 16:19

    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])
    end
    
    Capybara.javascript_driver = :chrome
    
    0 讨论(0)
  • 2021-02-20 16:23

    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.

    0 讨论(0)
提交回复
热议问题