Home >Web Front-end >JS Tutorial >Can Puppeteer Click Elements Based on Their Text Content?

Can Puppeteer Click Elements Based on Their Text Content?

DDD
DDDOriginal
2024-11-01 01:49:02624browse

 Can Puppeteer Click Elements Based on Their Text Content?

Clicking Elements with Text in Puppeteer

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()?

  • Using contains(text(), 'Text') may not return the expected results for certain scenarios, such as when the text is in child nodes.
  • Using contains(., 'Text') examines the element's entire content, including child nodes, providing more accurate results.

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!

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