How do you click on an element with text in Puppeteer?
You can exploit XPath along with page.$x()
in Puppeteer to identify and click any element through its text. Hereβs how you can have it done for a 'Example Text' linked element:
It spots an <a>
element having 'Example Text'. You can have the XPath modified as per different elements or text.
Dealing with sophisticated XPath
A more particular XPath comes to your rescue when you encounter difficult situations such as buttons or elements under divs. Example:
In here, we're aiming at a button carrying 'Button Text' within a div classed 'elements'. Usage of .
in place of text()
brings in all child node text, providing a playfield for a robust search.
Befriend whitespace and control case sensitivity
Thanks to XPath for normalize-space()
and translate()
functions, it can work around whitespace and case sensitivity ensuring your text conditions are adaptive:
This chunk of code will trigger a button click regardless of case sensitivity or whitespace.
Ditch XPath with pre-text selectors
Puppeteer 18.0.0 introduced text-prefixed selectors for those who are not fans of XPath:
Itβs way simpler than XPath approach and works amazingly when the text is non-nested.
Manage dynamic content
In terms of active web apps, you might face situations where elements are just not available on time. With Puppeteer, you don't need to worry! Use waitForXPath()
and waitForFunction()
:
Or wait for the matching text:
Quoting game: Advanced level
When aiming for text with quotes, don't forget to escape them properly:
Leverage CSS selectors with jQuery
If jQuery is enabled, you can use the :contains()
pseudoselector:
Safe and sound clicks
There might be times when you'd need to convert NodeList to an array or apply document.evaluate
for proper element actions:
Precise element interaction took place with NodeList turning into arrays, giving access to array methods.
Facts & Hazards
Know that XPath is case-sensitive and might be fragile when HTML structures change. Also, different Puppeteer versions may have different behaviors and syntax requirements, so always keep an eye on the current documentation.
Additional tips for the smart coder
- Use
result.iterateNext().click()
when you want XPath to step through possible matches. - Bring aboard puppeteer-select for an extra set of CSS selector capabilities, emulating jQuery's
:contains
CSS extension. - Add parent class to selectors for container-specificity to avoid ambiguous clicks on repeating text.
Was this article helpful?