Home > Web Front-end > JS Tutorial > body text

Can Puppeteer Click Elements Based on Their Text Content?

DDD
Release: 2024-11-01 01:49:02
Original
588 people have browsed it

 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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template