Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

183
Views
How to iterate selector over puppeter

Dear everybody I have a problem with selector in puppeter.

I have this code.

for(var k= 0 ; k<= 21 ; k++) {
  const text = await page.evaluate(() => {
    document.querySelector(
      'div.ui-table__row:nth-child('+k+') > a:nth-child(1) > div:nth-child(2)'
    ).textContent
  })
  console.log(text);            
}

The problem when I try to execute this snippet is that I don't have defined k but i think that is correct.

 Error: Evaluation failed: ReferenceError: k is not defined

How I can solve this problem ? Regards

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

k needs to be explicitly passed/injected into evaluate()

const k = 'foo'
await page.evaluate(k => {...}, k)

Change to:

for(var k= 0 ; k<= 21 ; k++) {
  const text = await page.evaluate((nth) => {
    document.querySelector(
      'div.ui-table__row:nth-child('+nth+') > a:nth-child(1) > div:nth-child(2)'
    ).textContent
  }, k)
  console.log(text);            
}
about 4 years ago · Juan Pablo Isaza Report

0

According to this document, You have to pass the variable as an argument to the page.evaluate like this:

const result = await page.evaluate((x) => { // 1. Define "x" to get value in the step 2
  return Promise.resolve(8 * x); // 3. Return the result
}, 7); // 2. Pass 7 to "x"
console.log(result); // prints "56"

Your snippet will look like this:

for(let k = 0; k <= 21; k++) {
  const text = await page.evaluate((nth) => {
    return document.querySelector(
      'div.ui-table__row:nth-child('+ nth +') > a:nth-child(1) > div:nth-child(2)'
    ).textContent; // Return `textContent` to "out side"
  }, k)
  console.log(text);            
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!