使用 puppeteer 对网页截图

有个对网页截图的需求,发现 puppeteer 挺好用的。

安装

npm i puppeteer

测试代码 a.js

const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch({
        headless: true,
        args: ['--use-gl=egl',  '--no-sandbox'],
        defaultViewport: {
            width: 1500,
            height: 3000,
            //hasTouch: true,
            //isMobile: true,
            deviceScaleFactor: 1,
        }

    });
    const page = await browser.newPage();
    await page.goto('https://www.wpcode.cn');

    await page.screenshot({
        path: 'example.png',
        fullPage:true,
    });

    let logo = await page.waitForSelector('#block-2');
    await logo.screenshot({
        path: 'example.jpg',
        quality: 99
    });

    await browser.close();
})();

运行

node a.js