Extracting element content and triggering clicks in Puppeteer

Hey folks! I’m trying to figure out how to grab the inner content of elements using Puppeteer. Even better, I’d love to know if there’s a way to click on elements that have specific text inside them.

Here’s a quick example of what I’m aiming for, but in regular JavaScript:

let elementFound = false

document.querySelectorAll('some-selector').forEach(elem => {
  if (!elementFound && elem.textContent.replace(/\D/g, '') === '5') {
    elem.click()
    elementFound = true
  }
})

Can anyone point me in the right direction for doing this with Puppeteer? Thanks a bunch for any tips or tricks you can share!

I’ve been working with Puppeteer for a while now, and I can share some insights on your question. For extracting element content, you can use the page.$eval() method. It’s pretty straightforward:

await page.$eval(‘selector’, el => el.textContent);

As for clicking elements with specific text, I’ve found this approach quite reliable:

await page.evaluate(() => {
const elements = document.querySelectorAll(‘selector’);
for (const el of elements) {
if (el.textContent.replace(/\D/g, ‘’) === ‘5’) {
el.click();
break;
}
}
});

This mimics your JavaScript example quite closely. Just remember to replace ‘selector’ with your actual selector. Hope this helps with your Puppeteer adventures!

hey dancingfox! for extracting content, try page.$$eval(‘selector’, els => els.map(e => e.textContent)). to click elements with specific text, you can use:

await page.evaluate(() => {
const elem = Array.from(document.querySelectorAll(‘selector’)).find(e => e.textContent.trim() === ‘desired text’);
if (elem) elem.click();
});

hope that helps! lemme know if u need more info