🧙‍♂️

Screenshot a web page in high resolution. Nodejs,puppeteer

2022/01/12に公開

Screenshot a web page in high resolution. Nodejs,puppeteer
高解像度でWEBページをスクリーンショット。

動作検証
Windows 10

使用方法 How to use

node "puppeteerScreenshot.js" url screenshot.png width height scaleFactor

node "puppeteerScreenshot.js" "https://fm-aid.com/bbs2/viewforum.php?id=2" "D:\\!TEMP\\screenshot.png" 640 480 3

puppeteerScreenshot.js

puppeteerScreenshot.js
puppeteer = require("puppeteer");

/*
let url = 'https://fm-aid.com/bbs2/';
let filePath ='D:\\!TEMP\\screenshot.png';
let w = 640;
let h = 480;
let scaleFactor = 2;
*/
for (let i = 0; i < process.argv.length; ++i) {
    console.log(i + ': ' + process.argv[i]);
}
let url = process.argv[2];
let filePath = process.argv[3];
let w = Number(process.argv[4]);
let h = Number(process.argv[5]);
let scaleFactor = Number(process.argv[6]);

(async () => {
    const browser = await puppeteer.launch({
        headless: true /*ブラウザ表示:false*/
        , timeout: 30000
        , defaultViewport: null /*デフォルト800x600|効かない?*/
        , args: [
            //'--start-maximized'  /*ウインドウ最大化*/
            `--window-size=${w},${h}`
            , `--force-device-scale-factor=${scaleFactor}`
            , '--no-sandbox', '--disable-setuid-sandbox'
            , '--disable-infobars'
        ]
        //,executablePath: 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'/*Chromium ではなく、Chromeを使用*/
        //,executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe'/*Chromium ではなく、Edgeを使用*/
        //,executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'/*Chromium ではなく、Chromeを使用*/
        //,userDataDir:'C:/Users/PCUSER/AppData/Local/Google/Chrome/User Data' //ユーザープロファイルを指定|要らない→/Default
    });
    const browserWSEndpoint = await browser.wsEndpoint();

    const page = (await browser.pages())[0];

    await page._client.send('Emulation.clearDeviceMetricsOverride');
    await page.goto(url, { waitUntil: "networkidle2" });

    const html = await page.content();

    await page.screenshot({
        path: filePath
    });
    await browser.close();
})(url, filePath, w, h, scaleFactor);

Discussion