如何让Puppeteer在goto()超时后仍能截取网页截图?
解决Puppeteer Core在AWS Lambda中截取重型页面的导航超时问题
针对你遇到的Navigation timeout of 30000 ms exceeded错误,我们可以通过捕获超时异常并继续执行截图的方式解决——既保留超时限制避免函数无限挂起,又能在超时后获取已加载的页面内容。
修改后的代码实现
// Create a browser instance const browser = await puppeteer.launch({ args: chromium.args, defaultViewport: chromium.defaultViewport, executablePath: await chromium.executablePath("./"), headless: chromium.headless, ignoreHTTPSErrors: true, }); // Create a new page const page = await browser.newPage(); // Set viewport width and height await page.setViewport({ width: pageWidth, height: pageHeight, deviceScaleFactor: scaleFactor }); // 处理导航超时,超时后继续截图 try { // 保留30秒超时限制,可根据需求调整 await page.goto(websiteURL, { timeout: 30000 }); } catch (error) { // 仅捕获导航超时类错误,其他异常正常抛出以排查问题 if (error.message.includes("Navigation timeout")) { console.log("页面加载超时,将截取已渲染内容"); } else { throw error; } } // Capture screenshot const screenshot = await page.screenshot(); // 清理浏览器资源,避免Lambda内存泄漏 await browser.close();
关键说明
- 异常精准处理:只针对导航超时错误做忽略处理,其他类型的错误(如网络中断、页面不存在)仍正常抛出,不影响问题排查。
- 超时后截图有效性:即使导航未完成,Puppeteer已渲染了页面的部分内容,此时调用
page.screenshot()依然能获取当前已加载的页面快照。 - 资源必做清理:添加
await browser.close()确保Lambda执行结束后释放浏览器资源,避免长期运行导致的内存溢出问题。
内容的提问来源于stack exchange,提问作者autotoon
相关产品推荐
相关产品推荐

