木偶异步$在try/catch外部引发eval错误



我试图使用Puppeter从列表中的元素中提取信息,但无法处理在try/catch.catch()中抛出的简单错误。

  • 一些item元素没有grandchild3
  • 当尝试用try/catch.catch()处理这些异常时,代码块通过,然后(在try/catch.catch()之外(value3返回ReferenceError,使程序崩溃

HTML:

<html>
<ul class=”list”>
<li class="item">
<div class="item_div">
<div class=”item_info”>
<h3 class=”grandchild1”>text</div>
<div class=”grandchild2”>text</div>
<div class=”grandchild3”>text</div>
</div>
</div>
</li>
</ul>
</html>

我遇到麻烦的木偶代码:

const testElementDetailList = await page.$$(".item")
for (let i = 0; i < testElementDetailList.length; i++) {
const value1 = await testElementDetailList[i].$eval(".grandchild1", el => el.innerText)
const value2 = await testElementDetailList[i].$eval(".grandchild2", el => el.innerText)
var value3 = undefined 
try {
value3 = await testElementDetailList[i].$eval(".grandchild3", el => el.innerText)
} catch (error) {
// handle value3 being undefined in html
}
console.log(value1)
console.log(value2)
console.log(value3)
}   

如何在设置value3时捕捉错误,并像在try/catch块中那样处理这些错误?

发现问题

referenceError似乎是由之前声明变量value3,然后在try-catch块内修改其值,然后在下面的console.log中调用它引起的。删除console.log内的调用解决了问题。

在最初发布这个问题之前,我读到异步导致try-catch出现问题,并认为这就是问题所在。

相关内容

最新更新