Home >Web Front-end >JS Tutorial >Can Puppeteer Click Elements Based on Their Text Content?
Question:
Can Puppeteer click on elements based on their text content, even if there is no unique identifier?
Short Answer:
Yes, you can click on elements containing specific text using XPath expressions.
Explanation:
XPath provides a way to query elements based on various criteria, including their text content. Here's how to use it in Puppeteer:
<code class="js">const [button] = await page.$x("//button[contains(., 'Button text')]"); if (button) { await button.click(); }</code>
This expression selects the first button element within the page that contains the text "Button text."
To also ensure the button is within the element with class "elements," add the following to the XPath expression:
<code class="js">const [button] = await page.$x("//div[@class='elements']/button[contains(., 'Button text')]");</code>
Why not text()?
The above is the detailed content of Can Puppeteer Click Elements Based on Their Text Content?. For more information, please follow other related articles on the PHP Chinese website!