团队一直在支持视频提链的需求,近期利用 chrome headless 进行升级,效率大大提升。那么 chrome headless 是什么呢?
通过官方更新日志了解到,在 Chrome 59 的版本加入了 headless 模式,所谓的 headless 就是一个无界面的浏览器,可以像有界面浏览器一样浏览网页,但无法直接看到页面。需要利用 Chrome 远程调试接口进行调试。
那么,提供这样一个无界面的浏览器有什么用呢?官方给的答案是这样的:
Why is that useful?
A headless browser is a great tool for automated testing and server environments where you don’t need a visible UI shell. For example, you may want to run some tests against a real web page, create a PDF of it, or just inspect how the browser renders an URL.
事实上,除了所描述的场景,还有更多的理由让你去使用它。
启动
首先确保你已经安装了 Chrome 59,本例在 macOS 中进行演示。
- 为了方便使用,首先在命令行工具中设置 Chrome 别名
alias chrome="/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome"
- 命令启动
chrome --headless www.baidu.com
更多的命令参数,请大家自行挖掘。
调试 UI 界面
如果想要调试 UI 界面,需要在启动时加上调试端口参数。
chrome --headless --remote-debugging-port=9222 www.baidu.com
这样,在有图形界面的 Chrome 中输入 http://localhost:9222 即可看到 Baidu 的首页了。
通过以上步骤,既可以启动 Chrome headless 模式,并进行调试了。如果你需要更多 API,可以使用 chrome-remote-interface 使用 Node.js 来写自己的处理程序。
in the end
团队使用 Chrome headless 模式进行各大视频网站的视频提链,效率极大提升,得益于这种 NO GUI 的浏览器的稳定以及丰富的调试 API。
以上。