Puppeteer之大屏批量截圖

polong發表於2018-10-22

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

    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之大屏批量截圖

Puppeteer之大屏批量截圖
Puppeteer之大屏批量截圖

相關文章