加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 如何在无头Chrome上使用Selenium Webdriver?

发布时间:2020-12-17 03:25:18 所属栏目:百科 来源:网络整理
导读:我正在学习使用Selenium来做基本的事情,例如截取屏幕,抓取和测试,并希望将它与无头Chrome一起使用,Chrome现在从Chrome 59开始就是稳定的. 我已经能够使用’selenium-webdriver’宝石和chromedriver截取屏幕截图,但不是无头. 这是我正在运行的ruby脚本,它在开
我正在学习使用Selenium来做基本的事情,例如截取屏幕,抓取和测试,并希望将它与无头Chrome一起使用,Chrome现在从Chrome 59开始就是稳定的.

我已经能够使用’selenium-webdriver’宝石和chromedriver截取屏幕截图,但不是无头.

这是我正在运行的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中设置无硒铬硒

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"

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读