无头的Chrome渲染整页

目前无头的Chrome的问题是,没有API来渲染整个页面,你只能得到你在CLI参数中设置的“窗口”。

我正在使用chrome-remote-interface模块,这是捕获的例子:

 const fs = require('fs'); const CDP = require('chrome-remote-interface'); CDP({ port: 9222 }, client => { // extract domains const {Network, Page} = client; Page.loadEventFired(() => { const startTime = Date.now(); setTimeout(() => { Page.captureScreenshot() .then(v => { let filename = `screenshot-${Date.now()}`; fs.writeFileSync(filename + '.png', v.data, 'base64'); console.log(`Image saved as ${filename}.png`); let imageEnd = Date.now(); console.log('image success in: ' + (+imageEnd - +startTime) + "ms"); client.close(); }); }, 5e3); }); // enable events then start! Promise.all([ // Network.enable(), Page.enable() ]).then(() => { return Page.navigate({url: 'https://google.com'}); }).catch((err) => { console.error(`ERROR: ${err.message}`); client.close(); }); }).on('error', (err) => { console.error('Cannot connect to remote endpoint:', err); }); 

要渲染整个页面,一个较慢的黑客解决scheme将是部分渲染。 设置固定的高度,滚动浏览页面,并在每X像素后截取屏幕截图。 问题是如何驱动滚动部分? 注入自定义JS还是可以通过Chrome远程接口实现?

你见过这个吗?

https://medium.com/@dschnr/using-headless-chrome-as-an-automated-screenshot-tool-4b07dffba79a

这听起来像是可以解决你的问题:

  // Wait for page load event to take screenshot Page.loadEventFired(async () => { // If the `full` CLI option was passed, we need to measure the height of // the rendered page and use Emulation.setVisibleSize if (fullPage) { const {root: {nodeId: documentNodeId}} = await DOM.getDocument(); const {nodeId: bodyNodeId} = await DOM.querySelector({ selector: 'body', nodeId: documentNodeId, }); const {model: {height}} = await DOM.getBoxModel({nodeId: bodyNodeId}); await Emulation.setVisibleSize({width: viewportWidth, height: height}); // This forceViewport call ensures that content outside the viewport is // rendered, otherwise it shows up as grey. Possibly a bug? await Emulation.forceViewport({x: 0, y: 0, scale: 1}); } setTimeout(async function() { const screenshot = await Page.captureScreenshot({format}); const buffer = new Buffer(screenshot.data, 'base64'); file.writeFile('output.png', buffer, 'base64', function(err) { if (err) { console.error(err); } else { console.log('Screenshot saved'); } client.close(); }); }, delay); }); 

Chrome远程界面支持使用input域模拟滚动手势。

 // scroll down y axis 9000px Input.synthesizeScrollGesture({x: 500, y: 500, yDistance: -9000}); 

更多信息: https : //chromedevtools.github.io/devtools-protocol/tot/Input/

您也可能对仿真域感兴趣。 DPD的答案包含一些现在删除的方法。 我相信Emulation.setVisibleSize可能适合你。

https://chromedevtools.github.io/devtools-protocol/tot/Emulation/