Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

page.$eval function in puppeteer always returning undefined

I'm using puppeteer and the function page.$(selector) to get the value. The function returns the error "Expected to get |string| or |function| as the first argument, but got "undefined" instead." I have tested the exact selector in Chrome's console and it works.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://stackoverflow.com/', {waitUntil: 'networkidle0'});
  try {
    const x = await page.$eval("body > header > div > ol.list-reset.grid.gs4 > li > a")
    console.log(firstArticle.text())
  } catch(err){
    console.log(err)
  }

  console.log(x.text())

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

What is the problem here?

like image 246
Nick Lee Avatar asked Jan 25 '23 20:01

Nick Lee


1 Answers

The function page.$eval() must receive two arguments, but you are sending only one. See the method signature:

page.$eval(selector, pageFunction[, ...args])

  • selector (string) A selector to query page for
  • pageFunction (function(Element)) Function to be evaluated in browser context
  • ...args (...Serializable|JSHandle) Arguments to pass to pageFunction
  • returns: (Promise(Serializable)) Promise which resolves to the return value of pageFunction

Try changing your code to:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://stackoverflow.com/', {waitUntil: 'networkidle0'});
  try {
    const elemText = await page.$eval("body > header > div > ol.list-reset.grid.gs4 > li > a", elem => elem.innerText)
    console.log('element innerText:', elemText)
  } catch(err){
    console.log(err)
  }
  await browser.close();
})();
like image 143
lcrespilho Avatar answered Jan 28 '23 11:01

lcrespilho