本文介绍了如何在无头Chrome上使用Selenium Webdriver?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习将Selenium用于诸如截图,抓取和测试之类的基本操作,并且希望将其与无头的Chrome配合使用,该Chrome现已从Chrome 59开始稳定.

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.

我已经能够使用'selenium-webdriver'gem和chromedriver来截屏,但并非无头.

I have been able to take a screenshot using the 'selenium-webdriver' gem and chromedriver, but not headless.

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

Here is the ruby script that I am running which hangs after starting to initialize the driver

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尝试此操作时,错误消息是

I have tried using the JavaScript and Python drivers with similar code and nothing works. When I try this with Python, the error message is

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 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"

这篇关于如何在无头Chrome上使用Selenium Webdriver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 01:11