$()
is not a standard function in JS, it's only a helper in Chrome devtools (page.evaluate
is not the same environment as Chrome Devtools):
Note: This API is only available from within the console itself. You cannot access the Command Line API from scripts on the page.
You should use instead document.querySelector()
.
Here is working example:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('http://github.com/', { waitUntil: 'networkidle2' });
const textOfFirstDiv = await page.evaluate(
() => document.querySelector('div').textContent
);
console.log(textOfFirstDiv);
await browser.close();
})();
Edit
You choose unfortunate example to explain your problem. If you want to extract JS value from page use it simply like this (Wikipedia has custom Geo
value in window
object)
await page.goto('https://en.wikipedia.org');
const geo = await page.evaluate(() => Geo);
console.log(geo);