Home > Web Front-end > JS Tutorial > How to Click an Element Based on Text Content Using Puppeteer?

How to Click an Element Based on Text Content Using Puppeteer?

Barbara Streisand
Release: 2024-10-29 07:30:30
Original
465 people have browsed it

How to Click an Element Based on Text Content Using Puppeteer?

Clicking on an Element with Text Using Puppeteer

Challenge: Locating and clicking an element based solely on its text content.

Consider the following HTML snippet:

<code class="html"><div class="elements">
    <button>Button text</button>
    <a href="#">Href text</a>
    <div>Div text</div>
</div></code>
Copy after login

Objective: Implement a click action on the button element that contains "Button text."

Solution:

The XPath expression below identifies the button containing the desired text:

"//button[contains(., 'Button text')]"
Copy after login

However, to ensure compatibility with the surrounding

container, use this modified expression:

"//div[@class='elements']/button[contains(., 'Button text')]"
Copy after login

To execute the click action:

const [button] = await page.$x(&quot;//div[@class='elements']/button[contains(., 'Button text')]&quot;);
if (button) {
    await button.click();
}
Copy after login

Explanation:

Using .contains(., 'Text') instead of .contains(text(), 'Text') XPath expression ensures that it includes child nodes, thus not excluding text nodes deeper in the element structure.

The above is the detailed content of How to Click an Element Based on Text Content Using Puppeteer?. For more information, please follow other related articles on the PHP Chinese website!

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