1

I am using Cheerio to parse the html and then running the following:

+$("#price1").text()|| +$("#price2").text() || undefined

Basically it tries to get the prices if the first fails and finally returns undefined if all fails.

How can I do the same thing in Puppeteer? I am not sure how to use page.evaluate to execute this chain of if-else commands. (I am also using Typescript as well.)

1 Answer 1

1

It seems the analog would be something like this:

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();

try {
  const [page] = await browser.pages();

  await page.goto('https://example.org/'); // your URL here

  const price = await page.evaluate(() => {
    const element = document.querySelector('#price1') ||
                    document.querySelector('#price2');
    if (element) return Number(element.innerText);
    return undefined;
  });
  console.log(price);
} catch(err) { console.error(err); } finally { await browser.close(); }
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thanks for the assist, but when I tried it, I get Property 'innerText' does not exist on type 'Element'.ts(2339), any idea how to solve this? When casting it to any, I am getting a NaN despite the price selectors being there as well..
I am sorry, I do not know TS(
There is also .textContent, but it is less readable sometimes: HTMLElement.innerText vs Node.textContent.
.textContent works (no complaints from Typescript) :D Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.