Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

puppeteer reference error in page.evaluate

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!

like image 611
GVB Avatar asked Dec 14 '22 17:12

GVB


1 Answers

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.

like image 87
Md. Abu Taher Avatar answered Dec 21 '22 09:12

Md. Abu Taher