事情的起因是客户三天两头的要求让我们给大屏截图,一定要最新的数据。所以我就自告奋勇研究了一下。
puppeteer是一款headless浏览器,由谷歌官方维护。先看看puppeteer入门 。思路是先打开所有链接,然后设置最长的等待时间,最后进行截图。(13版本puppeteer跟前一版api有挺多不同,headless设置为false,测试中headless为true不支持webgl绘制)。实现代码如下
const puppeteer = require('puppeteer');
const fs = require('fs');
(async() => {
const config = {
args: [
'--use-gl'
],
headless: false
}
const browser = await puppeteer.launch(config);
var info = [
{ url: 'https://developers.arcgis.com/javascript/latest/sample-code/visualization-point-styles/live/index.html', name: "a.jpeg" },
{ url: 'https://developers.arcgis.com/javascript/latest/sample-code/layers-custom-elevation-thematic/live/index.html', name: "b.jpeg" },
{ url: 'https://developers.arcgis.com/javascript/latest/sample-code/layers-imagery-pixelvalues/live/index.html', name: "c.jpeg" }
]
var that = this;
var length = info.length;
var a = [];
for (let j = 0; j < length; j++) {
var page = await browser.newPage();
await page.setViewport({ 4800, height: 1200 })
await page.goto(info[j].url);
a.push(page)
}
await a[0].waitFor(120 * 1000);
for (i = 0; i < length; i++) {
var item = info[i];
var url = item.url;
var name = item.name;
fs.exists(name, function(exists) {
console.log(exists ? fs.unlinkSync(name) : "no such file");
});
try {
await a[i].screenshot({ path: name });
console.log(name);
} catch (e) {
console.log(e)
}
}
await browser.close();
})();