Salman Srabon
Salman Srabon

Reputation: 247

How to take page access by puppeteer after clicking on href link?

Suppose, In a website I have some link to test that each link is working good.For that, I need to click each page link and need to test each page is opening and I need to assert the opened page content. How's that possible using puppeteer?

Upvotes: 1

Views: 430

Answers (1)

vsemozhebuty
vsemozhebuty

Reputation: 13802

If the links are common links with a href attribute, you can collect all URLs first and then test them in a loop like this:

const puppeteer = require('puppeteer');

(async function main() {
  try {
    const browser = await puppeteer.launch();
    const [page] = await browser.pages();

    await page.goto('https://example.org/');

    const hrefs = await page.evaluate(() => {
      return Array.from(
        document.querySelectorAll('a[href]'),
        a => a.href,
      );
    });

    for (const url of hrefs) {
      console.log(url);
      await page.goto(url);

      const data = await page.evaluate(() => {
        return document.title;
      });
      console.log(data);
    }

    await browser.close();
  } catch (err) {
    console.error(err);
  }
})();

Upvotes: 1

Related Questions