'Looping through id's in puppeteer [duplicate]
let scrapeProduct = async (url) => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto(url);
for(let i = 0;i < 10; i++) {
const [el] = await page.$x('//*[@id="spnGB27562Price"]')
const txt = await el.getProperty('textContent');
let rawTxt = await txt.jsonValue();
rawTxt = Number(rawTxt);
average += rawTxt;
}
return average / 10;
}
I'm trying to loop through the ID "spnGB27562Price". There are 10 id's (spnGB27562Price0 to spnGB27562Price9). It doesn't seem like I can add a variable in the xpath expression in my code. How would I go about this? I am just trying to average 10 numbers on a webpage.
Solution 1:[1]
You can simply use the back-tick (`) syntax to insert a variable into your xpath string like so:
const [el] = await page.$x(`//*[@id="spnGB27562Price${i}"]`);
Or you can alternatively just add two strings together with the use of single quotes ('):
const [el] = await page.$x('//*[@id="spnGB27562Price' + i + '"]);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ovidijus Parsiunas |
