0

Can someone please explain what might be going wrong here:

await page.click('some-selector-that-devtools-confirms-is-definitely-there')
let peeps = await page.evaluate(() =>
    {
        document.querySelector('some-selector-that-devtools-confirms-is-definitely-there')
    }
);
console.log('classes: '+peeps.classList)

I've tried page.wait...., to no avail, same error

Error

TypeError: Cannot read property 'classList' of undefined

Incidentally, is there a best practice for finding out if an element has a certain css class?

HellishHeat
  • 2,280
  • 4
  • 31
  • 37

2 Answers2

1

You have two problems here.

  1. You don't return document.querySelector('some-selector-that-devtools-confirms-is-definitely-there') so the variable peeps will be undefined

  2. You expect you can return any value with page.evaluate(). but acutely you can only return a serializable value, so it is not possible to return an element or NodeList back from the page environment using this method.

enter image description here


Example to return classlist by page.evaluate().

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto("https://google.com", { waitUntil: "networkidle2" });

  const classList = await page.evaluate(() => {
    return [...document.querySelector("div").classList];
  });

  console.log(classList);

  await browser.close();
})();
Ahmed ElMetwally
  • 2,276
  • 3
  • 10
  • 15
1

There are two main problems with your code:

  • Your evaluate method is not returning anything;
  • You need to access the classList inside the evaluate method

Here's an example:

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto("https://stackoverflow.com/");

  const classes = await page.evaluate(() => {
    return document.querySelector("body").classList;
  });

  console.log(classes);

  await browser.close();
})();

As an alternative approach, you could use getProperty("className"):

const puppeteer = require("puppeteer");

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto("https://stackoverflow.com/");

  const el = await page.$("body");
  const className = await el.getProperty("className");
  const classes = className._remoteObject.value.split(" ");

  console.log(classes);

  await browser.close();
})();
Bret Cameron
  • 451
  • 1
  • 4
  • 18