I'm trying to use for loop. But this error occurs. "ReferenceError: k is not defined" How can i fix the error?
let imageURL = [];
for (let k = 1; k <= images.length; k++) {
let data = await page.evaluate(() => {
let innerHTML = document.querySelectorAll('#__layout > main > div.nuxt-container > div > div:nth-child(3) > div.item-container > div:nth-child(72) > div > div.body > div.image-container > ul > li')[k].innerHTML;
let startIndex = innerHTML.indexOf('"') + 6;
let endIndex = innerHTML.lastIndexOf('"');
let imageLink = innerHTML.substring(startIndex, endIndex);
return {
image: imageLink,
};
});
imageURL.push(data);
}
Suppose that you are using puppeteer...
var a = 3;
await page.evaluate(() => {
// Here you cannot use 'a', since 'a' is in the context that is different than the context where this function is going to be executed (page context)
})
If you take a look at the api:
page.evaluate(pageFunction[, ...args])
You can see that the first argument is your function that will be executed in the page context. But you can see also, that you can have arguments (args) that will be passed to pageFunction.
Instead you should do:
var a = 4;
await page.evaluate((a) => {
// Now you can use outer 'a' variable through argument passed
}, a);
So if you have few arguments, accordingly:
await page.evaluate((k, startIndex, endIndex) => {
}, k, startIndex, endIndex);