1. 程式人生 > >Puppeteer之大屏批量截圖

Puppeteer之大屏批量截圖

const let 不同 style 分享圖片 cgi cti eva height

????事情的起因是客戶三天兩頭的要求讓我們給大屏截圖,一定要最新的數據。所以我就自告奮勇研究了一下。

????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({ width: 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();
})();

技術分享圖片

技術分享圖片
技術分享圖片

Puppeteer之大屏批量截圖