How to click on element with text in Puppeteer

Aleksandr Golubovskij picture Aleksandr Golubovskij · Nov 21, 2017 · Viewed 91.1k times · Source

Is there any method (didn't find in API) or solution to click on element with text?

For example I have html:

<div class="elements">
    <button>Button text</button>
    <a href=#>Href text</a>
    <div>Div text</div>
</div>

And I want to click on element in which text is wrapped (click on button inside .elements), like:

Page.click('Button text', '.elements')

Answer

tokland picture tokland · Jan 6, 2018

You may use a XPath selector with page.$x(expression):

const linkHandlers = await page.$x("//a[contains(text(), 'Some text')]");

if (linkHandlers.length > 0) {
  await linkHandlers[0].click();
} else {
  throw new Error("Link not found");
}

Check out clickByText in this gist for a complete example. It takes care of escaping quotes, which is a bit tricky with XPath expressions.