简体   繁体   中英

How to take screenshots for multiple pages automatically using Puppeteer

I have a list of URLs in the text file. I want to get the screenshot for each page automatically by reading each URL form the text file using Puppeteer.

const puppeteer = require('puppeteer');
async function doScreenCapture(url, site_name) {
    let browser = await puppeteer.launch({ headless: false });
    let page = await browser.newPage();
    await page.goto(url);
    await page.setViewport({width: 1382, height: 717})
    await page.waitFor(1000);
    console.log('do screen capture running');
    await page.screenshot({ path:`${site_name}.png`, fullPage: true });
    await page.close();
    await browser.close();
  }
async function run() {
    console.log('running');
    var fs = require("fs");
    var text = fs.readFileSync("linksList.txt").toString().split("\n");

    for (var i = 0; i < text.length; ++i) {
            doScreenCapture(text[i], "image"+i)
            console.log("image"+i+" completed");
            await page.waitFor(5000);
        }
 }

run();

This is the error I got while running the code

(node:77868) UnhandledPromiseRejectionWarning: ReferenceError: page is not defined at run at Object. at Module._compile (module.js:653:30) at Object.Module._extensions..js (module.js:664:10) at Module.load (module.js:566:32) at tryModuleLoad (module.js:506:12) at Function.Module._load (module.js:498:3) at Function.Module.runMain (module.js:694:10) at startup (bootstrap_node.js:204:16) at bootstrap_node.js:625:3 (node:77868) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) (node:77868) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. do screen capture running.

I see two issues here:

  • page does not exist in the "for" loop, only in the "run" function and that gives you the exception. You can move waiting to the function

  • "doScreenCapture" is an async function and you should use await doScreenCapture in order for pages to be open in succession, not at once.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM