Hi im learning puppeteer headless browser, but there is something that i dont understand
1) why i cant use a variable as a selector?
this works
const lastUpdate = await page.evaluate(() => document.querySelector('body > table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(3) > td:nth-child(2) > strong').textContent);
but this give me reference error LAST_UPDATE SELECTOR is not defined
const LAST_UPDATE_SELECTOR = 'body > table > tbody > tr:nth-child(2) > td > table > tbody > tr:nth-child(3) > td:nth-child(2) > strong';
const lastUpdate = await page.evaluate(() => document.querySelector(LAST_UPDATE_SELECTOR).textContent);
What im doing wrong? maybe there is something new that i need to learn
Thanks!
Pass the variable to the evaluate
function as an argument.
const selector = '#someSelector';
// 2. read the passed data
const lastUpdate = await page.evaluate((selector) => {
// 3. use it here
document.querySelector(selector).textContent,
// 1. Pass it here
}, selector);
What's going on?
.evaluate
accepts two arguments,pageFunction
, and the rest are serialized args
. When running the pageFunction, it passes the arguments to that, and then it becomes available inside the browser context.
Learn more about it on the puppeteer API docs.
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