Headless Chrome

Caution: Headless mode is available on Mac and Linux in Chrome 59Windows support is coming in Chrome 60. To check what version of Chrome you have, open chrome://version.

但是经过测试在windows版本的Chrome 60下使用headless命令仍然无效,Ubuntu Desktop下使用Chrome 60是可以的。

可以用下面的一些简单的命令测试:

chrome \
–headless \               # Runs Chrome in headless mode.
–disable-gpu \             # Temporarily needed for now.
–remote-debugging-port=9222 \
https://www.chromestatus.com   # URL to open. Defaults to about:blank.

Create a PDF

The –print-to-pdf flag creates a PDF of the page:

chrome –headless –disable-gpu –print-to-pdf https://www.chromestatus.com/

Taking screenshots

To capture a screenshot of a page, use the –screenshot flag:

chrome –headless –disable-gpu –screenshot https://www.chromestatus.com/

# Size of a standard letterhead.
chrome –headless –disable-gpu –screenshot –window-size=1280,1696 https://www.chromestatus.com/

# Nexus 5x
chrome –headless –disable-gpu –screenshot –window-size=412,732 https://www.chromestatus.com/
Running with –screenshot will produce a file named screenshot.png in the current working directory. If you’re looking for full page screenshots, things are a tad more involved. There’s a great blog post from David Schnurr that has you covered. Check out Using headless Chrome as an automated screenshot tool .

官方给出了几个在 CLI 环境中使用的简单例子,如果需要更复杂的应用,所以可以尝试使用下面这个npm 包编程:https://github.com/cyrus-and/chrome-remote-interface

那么这里要着重说一下,利用chrome的headless模式,需要同时使用Selenium和chromedriver吗?

通过协议直接操作真实浏览器

这就是Selenium的实现方式,通过WebDriver协议进行通信,浏览器和浏览器驱动都实现了C/S结构的WebDriver协议,Selenium通过浏览器的驱动包,来发送操作请求,浏览器根据请求响应相应的操作。这样实现有一个问题是始终有一个真实浏览器的界面在渲染和变化,一方面效率低下,另一方面在服务端环境无法运行。于是就衍生出了使用Xvfb(virtual framebuffer X Server) 来配合实现在服务器环境下的运行,基本解决了问题。但每一种浏览器的特性支持都依赖于相应的驱动的实现和支持情况。

无界面浏览器

前面的实现方式都或多或少有自己的问题或者局限,如果浏览器本身支持在服务端环境运行,这将是一个近乎完美的解决思路。Chrome 59开始支持无界面模式,Firefox 55支持Linux版的无界面模式,Firefox 56支持全平台的无界面模式,这样一来,使用方不用被动等待浏览器的WebDriver的实现。

总结一下:

利用Chrome headless mode,我们可以直接代替以前的Selenium+chromedriver。只是现在没有太多的第三方库封装,可能开发效率不高。但是估计Selenium等软件后续会积极支持的!

PS: PhantomJS原理和chrome headless mode原理差不多,只是chrome的开发团队更为强大,而且PhantomJS的一个核心开发者前一段时间因为Chrome要内置headless mode退出了开发该项目-_-!

References:

https://developers.google.com/web/updates/2017/04/headless-chrome

http://www.jianshu.com/p/aec4b1216011

http://imweb.io/topic/595bbbfdd6ca6b4f0ac71f14