Rtroman14
Rtroman14

Reputation: 328

How to check if element exists inside async / await with Puppeteer

I am having trouble recording an element on a page after checking if it exists. The block of code I'm referring to is under the "// phone" comment.

This code loops through each section (section of sections) on the page and records "company" and "phone." "Phone" may not be present in some sections so I figured I'd pass it through an if statement to check if it exists. This creates an error = "Error: failed to find element matching selector ".mn-contact-phone"" How do I solve this?

(async () => {
    try {
        const browser = await puppeteer.launch({ headless: true });
        const page = await browser.newPage();

        // loop through pages
        for (let pg = 1; pg < 5; pg++) {
            await page.goto("webpage");

            // record number of sections
            const sections = await page.$$("#mn-members-listings > div");

            // loop through each section
            for (const section of sections) {
                // company
                let company = await section.$eval(
                    "div.mn-searchlisting-title",
                    comp => comp.innerText
                );

                // phone --> THIS IF/ELSE THROWS AN ERROR
                if (section.$(".mn-contact-phone").length > 0) {
                    let phone = await section.$eval(".mn-contact-phone", phn => phn.innerText);
                } else {
                    let phone = "";
                }

                console.log(`Company = ${company} | Phone = ${phone}`);
            }
        }
        await browser.close();
    } catch (error) {
        console.log(`Our error is = ${error}`);
    }
})();

Upvotes: 3

Views: 8552

Answers (1)

mbit
mbit

Reputation: 3013

From puppeteer docs:

The method runs document.querySelector within the page. If no element matches the selector, the return value resolves to null.

1) null doesn't have length.

2) ElementHandle.$ returns a promise.

change the condition to:

if (await section.$(".mn-contact-phone"))

or if there are multiple elements:

if (await section.$$(".mn-contact-phone").length > 0)

Upvotes: 4

Related Questions