Home  >  Article  >  Web Front-end  >  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
Susan SarandonOriginal
2024-10-28 16:30:02852browse

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

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

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!

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