Home > Web Front-end > JS Tutorial > How to Click Elements Based on Text Content Using Puppeteer and XPath?

How to Click Elements Based on Text Content Using Puppeteer and XPath?

Susan Sarandon
Release: 2024-10-28 16:30:02
Original
952 people have browsed it

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();
Copy after login

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')]
Copy after login

Considerations

  • Ensure that the element contains the exact text string.
  • If the element is nested within a specific container, use an additional "/" to select the desired ancestor element. For instance, to click on a button inside a div:
//div[@class='container']/button[contains(., 'Button text')]
Copy after login

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

To click on the button, use:

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template