new to puppeteer and having trouble understanding how I can pass a variable to the browser inside the querySelector
I’ve got something to that goes and queries number of active users and returns the value
const usedLicenses = await page.evaluate(() => {
return document.querySelector('#root > div > main > div > div:nth-child(2) > div > div:nth-child(3) > strong').textContent;
});
If usedLicenses is not 0, I then wish to loop from 1 to whatever the value is to return some further info using this selector
Ignoring the loop requirement for a minute, it seems like I need something like this but how do I use the variable properly inside the selector?
const activeUsers = await page.evaluate(({usedLicenses}) => {
return document.querySelector('#root > div > main > div > div:nth-child(3) > ul > li:nth-child(usedLicenses) > div.title > strong').textContent;
},{usedLicenses});
Thanks
2
Answers
Like this, using template literal and the proper way to pass variable to
page.evaluate()
:And to full fill all the requirements:
As far as your post is not a MCVE: Minimal, Complete, and Verifiable Example, I’m not sure the argument to
li:nth-child()
will work.So, you need to adapt a bit if needed or edit your post to add missing informations.
In Puppeteer, when you’re passing a variable into the
page.evaluate()
function, you need to ensure that the variable is correctly referenced within the function. Since you’re passingusedLicenses
as an argument to evaluate(), you can access it inside the evaluate function directly by referencing it within the function’s scope.Here’s how you can pass the
usedLicenses
variable and use it inside the querySelector: