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
Barbara StreisandOriginal
2024-10-29 07:30:30461browse

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>

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')]"

However, to ensure compatibility with the surrounding

container, use this modified expression:

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

To execute the click action:

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

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:
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