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

2024-01-11

我正在学习使用 Selenium 进行一些基本操作,例如截屏、抓取和测试,并且希望将其与 Headless Chrome 一起使用,该 Chrome 从 Chrome 59 开始已经稳定。

我已经能够使用“selenium-webdriver”gem 和 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)

I found 这篇博文 https://intoli.com/blog/running-selenium-with-headless-chrome-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"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在无头 Chrome 上使用 Selenium Webdriver? 的相关文章

随机推荐