Puppeteer - How To Find A Link Element With A Certain Text?

Puppeteer is a NodeJS library that gives us control over headless Chrome APIs. With Puppeteer, it is much easier to automate UI tests of your website.

It is important to understand how Puppeteer works. Any task that you perform in a browser with the mouse actions can be programmed in headless Chrome. For eg. clicking a button or scrolling down a page or filling a form field. For programming these functionalities, Puppeteer first requires to locate the element on which it has to click or type etc. So, it needs a selector which can be an ID or Class or XPath etc. But, sometimes it is even hard to locate an element with these selectors. In those cases, you need to locate the element yourself.

We have already discussed how to set up and write your first test in Puppeteer here. In this article, we will discuss how to locate a link element with certain text.

Sometimes finding an element can be quite tricky in Puppeteer. The direct functions available in Puppeteer to locate an element with a certain ID, CSS class or XPath do not give desired results sometimes and will leave you with an error saying "Element not found". Hence, we do need more flexibility to find elements.

Let's say you have a website https://browsee.io/ and you wish to find a button with link text as "Let's Check It Out". We will go step by step in Puppeteer to find the link with the text "Let's Check It Out".

You need to open and close the browser at starting and end of every test as discussed in my previous blog here. After opening the browser and going to our specified URL i.e. https://browsee.io/ in this case, we will find all the elements with tag <a>. Once we have all the links, we will check for our specific text and return the link with our required text. This is how we can do that:

const puppeteer = require('puppeteer');

// Boilerplate stuff
async function startBrowser() {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  return {browser, page};
}

async function closeBrowser(browser) {
  return browser.close();
}

// Normalizing the text
function getText(linkText) {
  linkText = linkText.replace(/\r\n|\r/g, "\n");
  linkText = linkText.replace(/\ +/g, " ");

  // Replace &nbsp; with a space 
  var nbspPattern = new RegExp(String.fromCharCode(160), "g");
  return linkText.replace(nbspPattern, " ");
}

// find the link, by going over all links on the page
async function findByLink(page, linkString) {
  const links = await page.$$('a')
  for (var i=0; i < links.length; i++) {
    let valueHandle = await links[i].getProperty('innerText');
    let linkText = await valueHandle.jsonValue();
    const text = getText(linkText);
    if (linkString == text) {
      console.log(linkString);
      console.log(text);
      console.log("Found");
      return links[i];
    }
  }
  return null;
}

async function playTest(url) {
  const {browser, page} = await startBrowser();
  page.setViewport({width: 1366, height: 768});
  await page.goto(url);
  await findByLink(page, "Lets Check It Out");
  await page.screenshot({path: 'screenshot.png'});
  await closeBrowser(browser);
}

(async () => {
  await playTest("https://browsee.io/");
  process.exit(1);
})();

You need to run the program with:

node myfirsttest.js

and you can see the logs on the console:

Lets Check It Out
Lets Check It Out
Found

Here you can see that the element with text "Lets Check It Out" is found. You can also find a snapshot in the same folder with name screenshot.png.

Browsee Home Page


If you would like to know when your users face bugs or errors, please check out Browsee. It is user analytics platform where you can see how users actually used your site and learn from it.



How much is a great User Experience worth to you?


Browsee helps you understand your user's behaviour on your site. It's the next best thing to talking to them.

Browsee Product