0
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.

yamers
  • 11
  • 3
  • "It doesn't seem like I can add a variable in the xpath expression in my code" -- seems like basic string concatenation would work: `'//*[@id="spnGB27562Price' + i + '"]'`. Or use the backtick template literal syntax, but it's annoying to put into comments due to markdown. – ggorlen Apr 06 '22 at 20:13
  • 1
    @ggorlen backslash backtick to escape for comments \` \` – James Apr 06 '22 at 20:15

1 Answers1

0

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 + '"]);
Ovidijus Parsiunas
  • 2,512
  • 2
  • 8
  • 18