ruby - 如何在 headless Chrome 上使用 Selenium Webdriver?

标签 ruby selenium selenium-webdriver selenium-chromedriver headless-browser

我正在学习将 Selenium 用于基本操作,例如截屏、抓取和测试,并希望将其与 headless Chrome 一起使用,Chrome 59 现已稳定。

我已经能够使用“selenium-webdriver”gem 和 chromedriver 截取屏幕截图,但不是 headless 的。

这是我正在运行的 ruby​​ 脚本,它在开始初始化驱动程序后挂起

require 'rubygems'
require 'selenium-webdriver'

Selenium::WebDriver.logger.level = :debug
p 'initializing driver'
driver = Selenium::WebDriver.for :chrome, switches: %w[--headless --disable-gpu --screenshot --hide-scrollbars]
p 'navigating to Google'
driver.navigate.to "http://google.com"  
driver.save_screenshot("./screen.png")
driver.quit

以及日志的输出:

:> ruby rubytest.rb
"initializing driver"
2017-06-07 15:55:43 DEBUG Selenium Executing Process 

["/Users/name/Documents/scrapings/python/env/bin/chromedriver", "--port=9515"]
2017-06-07 15:55:43 DEBUG Selenium polling for socket on ["127.0.0.1", 9515]
Starting ChromeDriver 2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b) on port 9515
Only local connections are allowed.
2017-06-07 15:55:43 INFO Selenium -> POST session
2017-06-07 15:55:43 INFO Selenium    >>> http://127.0.0.1:9515/session | {"desiredCapabilities":{"browserName":"chrome","version":"","platform":"ANY","javascriptEnabled":true,"cssSelectorsEnabled":true,"takesScreenshot":false,"nativeEvents":false,"rotatable":false,"chromeOptions":{"args":["--headless","--disable-gpu","--screenshot","--hide-scrollbars"]}}}
2017-06-07 15:55:43 DEBUG Selenium      > {"Accept"=>"application/json", "Content-Type"=>"application/json; charset=utf-8", "Content-Length"=>"284"}
[RUBY BACKTRACE TO DRIVER INITIALIZATION]

我尝试过使用具有类似代码的 JavaScript 和 Python 驱动程序,但没有任何效果。当我用 Python 尝试这个时,错误消息是

WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
  (Driver info: chromedriver=2.29.461585 (0be2cd95f834e9ee7c46bcc7cf405b483f5ae83b),platform=Mac OS X 10.12.5 x86_64)

最佳答案

我找到了 this blog post对于在 ruby​​ 中使用 selenium 设置 headless chrome 很有用

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"

关于ruby - 如何在 headless Chrome 上使用 Selenium Webdriver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44424200/

相关文章:

ruby-on-rails - Heroku 上不受信任的证书

ruby-on-rails - youtube_it 在更新到 Ruby 2 后抛出 ArgumentError - 如何修复?

javascript - Selenium - 如何在 JS 测试文件中使用 JavascriptExecutor?

Python - Selenium PhantomJS - JSON 错误

python - 关闭 Selenium 中的通用弹出窗口

ruby-on-rails - Rails MySQL ILIKE 查询

ruby-on-rails - 独立 ruby​​ 脚本的配置文件

java - 如何在 Selenium-Java Webdriver 测试项目中指定 Java 类的执行顺序

c# - XPath 从当前元素查找动态父/祖先元素?

python - 防止 Firefox 附加组件第一页显示