Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an element contains a certain string in puppeteer?

I'm trying to find out if an element #view_container > div > div > div.pwWryf.bxPAYd > div > div.WEQkZc > div > form > content > section > div > content > div.ck6P8 > div > div contains a certain set of characters (•••). I'm pretty new to coding so any help would be greatly appreciated.

like image 693
Seth Robinson Avatar asked Jan 23 '19 04:01

Seth Robinson


People also ask

How do you find the value of an element in a puppeteer?

page. $eval() function is used to get the value for an element in puppeteer. $eval will stage two-parameter as an argument first parameter will be the selector and the second parameter will be element= element.

How do you get the puppeteer element text?

We can get element text in Puppeteer. This is done with the help of the textContent property. This property of the element is passed as a parameter to the getProperty method.


2 Answers

Something like this:

'use strict';

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch();
    const [page] = await browser.pages();

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

    const stringIsIncluded = await page.evaluate(() => {
      const string = '...';
      const selector = 'p > a[href]';
      return document.querySelector(selector).innerText.includes(string);
    });

    console.log(stringIsIncluded);

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();

You can use .textContent instead of .innerText if you need element's raw text with all the white spaces not normalized to be checked.

like image 159
vsemozhebuty Avatar answered Nov 05 '22 07:11

vsemozhebuty


Have a look at $$eval

page.$$eval('#view_container > div', (elements) =>
  elements.some((el) => el.textContent.includes('some text'))
);
like image 41
B12Toaster Avatar answered Nov 05 '22 09:11

B12Toaster