Home  >  Article  >  Web Front-end  >  How to Click Elements with Specific Text Using Puppeteer?

How to Click Elements with Specific Text Using Puppeteer?

DDD
DDDOriginal
2024-10-30 01:23:02281browse

How to Click Elements with Specific Text Using Puppeteer?

Click on Elements with 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.

XPath Expression Solution

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>

Explanation

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn