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?
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();
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With