0

I am currently struggling in a way to get the variable "index" defined in the variable "name", it everytime returns "undefined" while it shouldn't. I know that i am i an async function but this case is weird and i cannot get it to work.

I have the following :

const puppeteer = require('puppeteer');


(async function main() {
    try {
        for (var index = 1; index < 20; index++) {
            console.log(index)
            const browser = await puppeteer.launch();
            const [page] = await browser.pages();

            await page.goto(`MYSITE`);

            var name = await page.evaluate(() => {
                return document.querySelector(`#itembanking-list > tbody > tr:nth-child(${index}) > td:nth-child(2)`).innerText;
            })

            await browser.close();
        }
    } catch (err) {
        console.error(err);
    }
})();

When running the following code, i am getting this error :

Error: Evaluation failed: ReferenceError: index is not defined

How can i get the variable "index" defined in "name" ?

Zayonx
  • 164
  • 1
  • 12
  • how to do you know it's undefined ? did you try that query selector on actual page ?may be the selecter isn't correct – Madhawa Priyashantha Feb 24 '19 at 12:30
  • It is correct. I know that is it undefined because when i run the following code, it returns me 'Error: Evaluation failed: ReferenceError: index is not defined' – Zayonx Feb 24 '19 at 12:33
  • 6
    Possible duplicate of [Puppeteer: pass variable in .evaluate()](https://stackoverflow.com/questions/46088351/puppeteer-pass-variable-in-evaluate) – Madhawa Priyashantha Feb 24 '19 at 12:35
  • 1
    inside page evaluate function you cannot access your variable but actual page varibles.if you want to use a varible you should pass it to the evaluate function like this `await page.evaluate((index)` see the duplicate question for more details – Madhawa Priyashantha Feb 24 '19 at 12:38

1 Answers1

1

You should pass the index variable as second param in evaluate and handle it in callback

await page.evaluate(index => {...code}, index)