[英]How to take screenshots for multiple pages automatically using Puppeteer
我在文本文件中有一個 URL 列表。 我想通過使用 Puppeteer 從文本文件中讀取每個 URL 來自動獲取每個頁面的屏幕截圖。
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();
這是我在運行代碼時遇到的錯誤
(node:77868) UnhandledPromiseRejectionWarning: ReferenceError: page is not defined at run at Object. 在 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 bootstrap_node.js (bootstrap_node.js:204:16) at bootstrap_node.js :625:3 (node:77868) UnhandledPromiseRejectionWarning:未處理的承諾拒絕。 這個錯誤要么是因為在沒有 catch 塊的情況下拋出了異步函數,要么是因為拒絕了一個沒有用 .catch() 處理過的承諾。 (rejection id: 1) (node:77868) [DEP0018] DeprecationWarning:不推薦使用未處理的承諾拒絕。 將來,未處理的承諾拒絕將使用非零退出代碼終止 Node.js 進程。 做屏幕截圖運行。
我在這里看到兩個問題:
page
不存在於“for”循環中,只存在於“run”函數中,這給了你例外。 您可以移動等待功能
“doScreenCapture”是一個異步函數,您應該使用await doScreenCapture
以便連續打開頁面,而不是一次打開。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.