I'm trying to use Puppeteer to extract information from elements in a list, but can't handle simple error being thrown in try/catch or .catch().
- Some
itemelements don’t havegrandchild3 - When trying to handle these exceptions with
try/catchor.catch(), the code block passes, then (outsidetry/catchand.catch())value3returns aReferenceError, crashing the program.
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>
Puppeteer code I'm having trouble with:
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)
}
How can I catch errors when setting value3, and handle these like in a try/catch block?