Home > Article > Web Front-end > How to Click Elements with Specific Text Using Puppeteer?
This question explores a solution for clicking on elements that contain specific text in Puppeteer. Despite the API not explicitly providing a method for this, various approaches can be employed.
A robust method is to use XPath expressions. For instance, to select a button with the text "Button text" within a div with the class "elements," use this expression:
<code class="js">const [button] = await page.$x("//div[@class='elements']/button[contains(., 'Button text')]");</code>
Using the "text()" node in XPath can be problematic due to its limitations in handling multiple texts. Instead, the "contains(" expression with "." as the second argument searches for text within the element itself and its children. This ensures that both "Start" and "End" are found in the example provided.
The above is the detailed content of How to Click Elements with Specific Text Using Puppeteer?. For more information, please follow other related articles on the PHP Chinese website!