Home > Blockchain >  How to iterate selector over puppeter
How to iterate selector over puppeter

Time:12-21

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

CodePudding user response:

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);            
}

CodePudding user response:

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);            
}
  • Related