捕获 waitForSelector 错误

tof*_*nns 4 javascript automation ui-automation node.js puppeteer

我使用一个名为Puppeteer的模块

我尝试在我的页面上等待一个可能不会出现的选择器。在我采用的两种方法中,只有 try-catch 方法有效。

try-catch 块 - 工作

try {
    await page.waitForSelector('.element');
    //element appeared
} catch (error) {
    //element did not appear
}
Run Code Online (Sandbox Code Playgroud)

承诺链 - 不工作

await page.waitForSelector('.element')
    .catch((error) => { 
        //element did not appear
    })
    .then(() => {
        //element appeared
    });
Run Code Online (Sandbox Code Playgroud)

看起来 waitForSelector确实返回了 API 中指示的 Promise,但我不明白为什么后一种方法不起作用。无论如何它抛出了错误。

有没有人遇到过同样的问题?

Gra*_*ler 5

您应该重构 Promise Chaining 示例以在then()方法之前使用catch()方法。

考虑使用以下示例page.waitForSelector()

// Correct Method
await page.waitForSelector('#example').then(() => {
  console.log('SUCCESS');
}).catch(e => {
  console.log('FAIL');
});
Run Code Online (Sandbox Code Playgroud)

如果元素不存在,FAIL则将被记录到控制台。否则,如果该元素确实存在,则输出将为SUCCESS

另一方面,看看下面的例子,其中then()catch()被颠倒了:

// Incorrect Method
await page.waitForSelector('#example').catch(e => {
  console.log('FAIL');
}).then(() => {
  console.log('SUCCESS - not necessarily');
});
Run Code Online (Sandbox Code Playgroud)

如果元素不存在,FAIL则将记录到控制台,但无论元素是否存在,SUCCESS也会写入控制台。这是因为SUCCESS在尝试捕获错误后,日志记录是链中的下一个直接步骤。

使用then()beforecatch()将允许您打印两条消息之一并获得所需的结果。