Puppeteer Async .$eval throwing error outside try/catch

Viewed 33

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 item elements don’t have grandchild3
  • When trying to handle these exceptions with try/catch or .catch(), the code block passes, then (outside try/catch and .catch()) value3 returns a ReferenceError, 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?

1 Answers

Found the issue

The referenceError seemed to be caused by declaring variable value3 before, then modifying it's value inside the try catch block, then calling it below in the console.log. Deleting the call inside the console.log solved the issue.

Before initially posting this question i read about async causing problems with try catch, and believed this to be the issue.

Related