本文主要总结一些在命令行中使用Chrome的headless mode的tips。在本文中Chrome的执行文件统一使用chrome。本文会不断更新。
在一个独立的路径下载、安装和使用Chrome
可以通过以下脚本在ubuntu中下载最新版本的Chrome,并且安装到一个独立路径中直接使用,从而可以避免与其他的chrome版本发生冲突。
# 安装一些必要的lib
sudo apt install libgbm-dev
# 下载安装
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
dpkg-deb -x google-chrome-stable_current_amd64.deb google-chrome
# 使用chrome
google-chrome/opt/google/chrome/chrome --headless=new https://example.com
使用新的headless模式
在2021年之后的Chrome实现中统一了headless模式headful模式,所以可以通过指定--headless=new来启动新的headless实现模式:
chrome --headless=new https://example.com
默认情况下,在--headless不指定模式则是启动原有的headless模式,等同于指定了--headless=old参数。
基础使用
在命令行中,可以通过Chrome的headless模式导出DOM,导出PDF,和导出截图。
# 导出DOM到STDOUT
chrome --headless=new --dump-dom https://example.com/ > dom.html
# 导出截图到screenshot.png
chrome --headless=new --screenshot --window-size=1600,900 https://example.com/
# 导出PDF到output.pdf
chrome --headless=new --print-to-pdf https://example.com/
禁止GPU的使用
在一些服务器中,因为不能使用GPU,所以运行Chrome时会存在抛出一些warning或者错误,比如
[475664:8:1221/012131.519627:ERROR:command_buffer_proxy_impl.cc(127)] ContextResult::kTransientFailure: Failed to send GpuControl.CreateCommandBuffer
这时可以禁止掉GPU的使用:
chrome --headless=new --disable-gpu --dump-dom https://example.com