Home > Article > Web Front-end > How to Click Elements Based on Text Content Using Puppeteer and XPath?
Clicking Elements by Text with Puppeteer
In Puppeteer, clicking on specific elements based on their text content can be achieved using XPath expressions.
How to Click Elements with Text
To click on an element with specific text, use the following XPath expression:
const [element] = await page.$x("//element[contains(., 'text')]"); await element.click();
Replace "element" with the appropriate tag name (e.g., "button" or "a"), and "text" with the desired substring to match. For example:
//button[contains(., 'Button text')]
Considerations
//div[@class='container']/button[contains(., 'Button text')]
XPath vs. Text()
The XPath expression contains(., 'Text') uses the element's child nodes to match the specified text. In contrast, contains(text(), 'Text') only considers the element's text content.
Example
Given the following HTML:
<div class="elements"> <button>Button text</button> <a href="#">Href text</a> <div>Div text</div> </div>
To click on the button, use:
const [button] = await page.$x("//div[@class='elements']/button[contains(., 'Button text')]"); await button.click();
The above is the detailed content of How to Click Elements Based on Text Content Using Puppeteer and XPath?. For more information, please follow other related articles on the PHP Chinese website!