Al Mllyrs
Al Mllyrs

Reputation: 33

Puppeteer page.$eval throws an error if element with selector wasn't found

I'm doing a webscraper which goes in several pages. I want to know if it's possible to ignore an error thrown when my selector doesn't exist in my current page. Most of the time, .lot-page__lot__sold exist, but sometimes not and that throw me an error

The error says:

UnhandledPromiseRejectionWarning: Error: Error: failed to find element matching selector ".lot-page__lot__sold"

 const rawSoldPrice = await page
    .$eval(".lot-page__lot__sold", (text) => text.textContent)
    .catch((err) => true);

What should I change in the code?

Upvotes: 3

Views: 3073

Answers (1)

Abbas
Abbas

Reputation: 1255

Use page.evaluate instead, as page.$eval absolutely needs the element to exist.

const elementTextContent = await page.evaluate(() => {
  const element = document.querySelector('.lot-page__lot__sold')
  if (element) {
    return element.textContent
  }

  return '';
})

Upvotes: 4

Related Questions