我在使用 waitForXpath
等待一个不总是显示的元素时遇到问题。
const isElementShown = await page
.waitForXPath('/html/body/div[4]/div[2]/iframe', {
visible: true,
timeout: 12000,
})
.then(result => {
console.log(`element shown: ${result}`);
return result;
})
.catch(exception => console.log(`element not shown: ${exception}`));
if (isElementShown) {
// do something
}
即使我有 .catch()
,该函数也会停止执行并在此处捕获异常:
process.on('unhandledRejection', (reason: { stack: unknown }, promise) => {
try {
console.log(`SYSTEM WIDE UNHANDLED REJECTION: ${reason.stack}`);
return reportError_async(`${reason.stack}`);
} catch (exception) {
console.log('exception', exception);
}
return null;
});
异常信息是:
Error: target should exist before targetInfoChanged
使用 Puppeteer v9.1.0
答案 0 :(得分:0)
如果你需要这一切只是因为你有这个条件:
if (isElementShown) {
// do something
}
为什么不使用 page.$()
?
const isElementShown = await page.$('html > body > div:nth-child(4) > div:nth-child(2) > iframe');
if (isElementShown) {
// do something
}
如果没有找到元素,它不会抛出任何异常。但是,您不能在这里使用 xPath,只能使用 here 的 CSS 选择器,但这不应该是一个麻烦。
答案 1 :(得分:0)
看起来这是 9.1.0
版本的 Puppeteer 的问题。版本 9.1.1
解决了该问题。
相关的 Github 问题:https://github.com/puppeteer/puppeteer/pull/7203