当前无头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);
});
要渲染整个页面,一个较慢且黑客的解决方案是部分渲染。设置固定高度并滚动页面并在每个X像素后截取屏幕截图。问题是如何驱动滚动部分?注入自定义JS会更好吗?还是可以通过Chrome远程界面实现?
答案 0 :(得分:1)
Chrome远程界面支持使用输入域模拟滚动手势。
// 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/
答案 1 :(得分:0)
你见过这个吗?
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);
});