Get the a-tag href in Puppeteer (selector, XPath)

Published:  

nodejs puppeteer


This is how to get the value of the href attribute of the a tag in Puppeteer.
I write about how to do it in selectors and in XPath.

Environment

  • Node.js v12.18.1
  • puppeteer v4.0.1

How to get it using selectors

Get from multiple a tags.

const hrefs = await page.$$eval("a.link", (list) => list.map((elm) => elm.href));
// → <Array<string>>

Get it from a single a tag.

const href = await page.$eval("a.link", (elm) => elm.href);
// → <string>

How to get it using XPath

Get from multiple a tags.

const hrefs = await Promise.all((await page.$x('//a[@class="link"]')).map(async item => await (await item.getProperty('href')).jsonValue());
// → <Array<string>>

Reference

Here is the official documentation.