所以我读到一些错误和https ERR_CONNECTION_CLOSED。我担心的是我该如何处理木偶戏?
我当前的问题是,如果发生此错误,木偶戏实际上会等待10分钟,直到最终抛出。浏览器只显示正在等待....,它一直在等待。
我尝试了Navigationtimeout,但这似乎不能解决问题。无论如何要迫使伪娘更早地停止,而不是仅仅无限期地等待页面?
答案 0 :(得分:0)
由于puppeteer大量使用异步函数,因此使用try ... catch可以很好地处理其错误。示例:
// when inside an async function:
// supose I have access to `browser` and `page` objects here, outside try...catch
try {
// do something with browser/page that may result in errors. Example:
const response = await page.goto('https://www.google.com', { waitUntil: 'load', timeout: 10000 });
// do something with the results...
catch (error) {
// if something in the "try" fails, you have access to `page` and `browser` objects here
// and you can treat the errors, or simply log to console and close the page/browser. E.g.:
if (error.message.includes('ERR_CONNECTION_CLOSED')) {
console.log('Oopps...');
await page.close();
await browser.close();
} else {
// try again, maybe...
}
}
如果您喜欢使用传统的.then()和.catch()承诺方法,则可以执行类似的操作:
const puppeteer = require('puppeteer');
puppeteer.launch()
.then(browser => browser.newPage()
.then(page => page.goto('https://aldfkjasldfj')
.then(response => {
// do something with the response if all is good
})
.catch(reason => {
console.log(reason.message);
console.log('closing the page and the browser');
page.close().then(() => browser.close());
})
)
);
非常抱歉上述代码。您会看到.then()和.catch()非常难看。 :)我更喜欢异步/等待。
答案 1 :(得分:0)
await page.goto("https://www.example.com" , {
waitUntil: 'domcontentloaded'
}).catch(err => {
if(err.message.includes("ERR_PROXY_CONNECTION_FAILED") || err.message.includes("ERR_TUNNEL_CONNECTION_FAILED")){
return "ERR_PROXY_FAILED";
}else if(err.message.includes("Navigation Timeout")){
return "ERR_SLOW_CONNECTION";
}else if(err.message.includes("Protocol error")){
return "ERR_UNKNOWN_PROTOCOL";
}else{
throw err;
}
});