This is one of the most common interview questions that gets asked during interviews for QA Automation/SDET.
Let’s tackle this problem using Playwright. We’ll take an example of a page, which has a lot of links and then see if we’re able to get the href
tags for all of them.
The links in a page are tagged under the a
(anchor) tag, and with the attribute href
. So to get all the links count, we have to fetch all the href
attributes for the a
tag.
We’ll take the example of SelectorsHub Xpath practice page. If you haven’t heard about SelectorsHub, you should check it out. It is a nifty tool for QA automation engineers and it is not just a single tool – there is a whole ecosystem around it.
Coming back to the problem – we can use the map
method of the JS to get the array of the href
, using the page.evalulate()
method.
const hrefs = await page.evaluate(() => {
return Array.from(document.links).map(item => item.href);
});
This will create a new array containing the href
, since map
method creates a new array, using the page.evaluate
method from the Playwright.
Sample code
import { chromium,test } from "@playwright/test";
test('Launch the Selectors hub test page',async()=>{
const browser = await chromium.launch({
headless: false
});
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("https://selectorshub.com/xpath-practice-page/");
await page.waitForSelector('.dropbtn',{
state: "visible"
});
const hrefs = await page.evaluate(() => {
return Array.from(document.links).map(item => item.href);
});
await console.log(`There are ${hrefs.length} links on the page`);
});
Gives this output as below. –
