Search code examples
web-scrapingxpathpuppeteerhrefcontains

How add const to await page.$x in puppeteer Node.js? Const in xpath


I want to add cont to href link. I want to use const. I had problem with:

const klik2 = await page.$x("//a[contains(@href, 'p2')]");

I want to add

const new = 'p' + [i];

Where now is 'p2'. How do it correctly ?

My actual code:

const puppeteer = require('puppeteer');

(async () => {

const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.setDefaultNavigationTimeout(0);
await page.goto("http://mypage.test/");
for (let i = 1; i < 100; i++) {
const link = 'p' + [i];
try {

const klik2 = await page.$x("//a[contains(@href, link)]");
await klik2[0].click();

} catch {

   console.log(e);    

}

   await page.goto("http://mypage.test/");


})();

Also had trying something like this:

const klik3 = "'" + 'p1' + "'";
const klik = '"//a[contains(@href,' + klik3 + ')]"';
console.log(klik);
const klik2 = await page.$x(klik);
await klik2[0].click();

Solution

  • You can use template literals (template strings). Also, it seems you do not need an array in your concatenation (here: const link = 'p' + [i];)

    const link = 'p' + i;
    try {
      const klik2 = await page.$x(`//a[contains(@href, '${link}')]`);
      await klik2[0].click();
    }