Headless-Chrome
Headless Chrome 实战:动态渲染、页面抓取与端到端测试
笔者往往是使用
环境配置
在
$ chrome --headless --remote-debugging-port=9222 https://chromium.org
笔者为了部署方便,使用
docker run -d -p 9222:9222 justinribeiro/chrome-headless
如果是在
alias chrome="/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome"
alias chrome-canary="/Applications/Google\ Chrome\ Canary.app/Contents/MacOS/Google\ Chrome\ Canary"
alias chromium="/Applications/Chromium.app/Contents/MacOS/Chromium"
如果是在
# Install Google Chrome
# https://askubuntu.com/questions/79280/how-to-install-chrome-browser-properly-via-command-line
sudo apt-get install libxss1 libappindicator1 libindicator7
wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
sudo dpkg -i google-chrome*.deb# Might show "errors", fixed by next line
sudo apt-get install -f
--dump-dom
参数可以将 document.body.innerHTML
打印到标准输出中:
chrome --headless --disable-gpu --dump-dom https://www.chromestatus.com/
而 --print-to-pdf
标识则会将网页输出位
chrome --headless --disable-gpu --print-to-pdf https://www.chromestatus.com/
初次之外,我们也可以使用 --screenshot
参数来获取页面截图:
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/
如果我们需要更复杂的截图策略,譬如进行完整页面截图则需要利用代码进行远程控制。