我正试图用木偶戏截取屏幕截图。
我对未处理的承诺拒绝错误有很多麻烦。 我浏览了许多论坛和主题,提出了许多不同的内容,我申请了这些内容。
这些建议的范围从使用异步函数到使用try-catch块。
经过改进,这是我的代码的最终版本:
const puppeteer = require('puppeteer');
async function getPic() {
const browser = await puppeteer.launch(/*{headless: false}*/);
const page = await browser.newPage();
page.setViewport({width: 1000, height: 500});
process.on("unhandledRejection", (reason, p) => {
console.error("Unhandled Rejection at: Promise", p, "reason:", reason);
browser.close();
});
try{
await page.goto('https://www.google.com');
}
catch (error) {
console.log(error);
browser.close();
}
await page.screenshot({path: 'pic.png'});
await broswer.close();
}
getPic();
虽然,它仍然不起作用,我收到此错误消息:
Error: Navigation Timeout Exceeded: 30000ms exceeded
at Promise.then (C:\...\pupet test\node_modules\pupp
eteer\lib\NavigatorWatcher.js:71:21)
at <anonymous>
Unhandled Rejection at: Promise Promise {
<rejected> { Error: Protocol error (Target.sendMessageToTarget): Target closed
.
at Promise (C:\...\pupet test\node_modules\puppeteer
\lib\Connection.js:198:56)
at new Promise (<anonymous>)
at CDPSession.send (C:\...\pupet test\node_modules\p
uppeteer\lib\Connection.js:197:12)
at Page._screenshotTask (C:\...\pupet test\node_modu
les\puppeteer\lib\Page.js:707:24)
at <anonymous>
message: 'Protocol error (Target.sendMessageToTarget): Target closed.' } } rea
son: { Error: Protocol error (Target.sendMessageToTarget): Target closed.
at Promise (C:\...\pupet test\node_modules\puppeteer
\lib\Connection.js:198:56)
at new Promise (<anonymous>)
at CDPSession.send (C:\...\pupet test\node_modules\p
uppeteer\lib\Connection.js:197:12)
at Page._screenshotTask (C:\...\pupet test\node_modu
les\puppeteer\lib\Page.js:707:24)
at <anonymous>
message: 'Protocol error (Target.sendMessageToTarget): Target closed.' }
答案 0 :(得分:2)
您需要正确使用async-await。您正在以同步方式调用异步函数。
这是经过适当等待的修改后的代码。阅读下面的代码,看看有什么不对。
const puppeteer = require('puppeteer');
async function getPic() {
try{ // <-- wrap the whole block in try catch
const browser = await puppeteer.launch(/*{headless: false}*/);
const page = await browser.newPage();
await page.setViewport({width: 1000, height: 500}); // <-- add await here so it sets viewport after it creates the page
await page.goto('https://www.google.com');
await page.screenshot({path: 'pic.png'});
await broswer.close(); // <-- close browser after everything is done
} catch (error) {
console.log(error);
}
}
getPic();
错误表示它已超时,这意味着它甚至无法加载网站。尝试检查页面是否在浏览器上正确加载。