Home >Web Front-end >JS Tutorial >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
"//div[@class='elements']/button[contains(., 'Button text')]"
To execute the click action:
const [button] = await page.$x("//div[@class='elements']/button[contains(., 'Button text')]");
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!