Search code examples
puppeteerpuppeteer-sharp

Puppeteer (PuppeteerSharp) How to click?


How to click on an element if all id's are random? Unique - only text with description.

This is a list that contains various items that you can click with the mouse. I can't figure out how to make this click, for example, on an element containing the text "Some Unique Text 3"

<section class="css-1kyhqub">
    <ul data-testid="categories-list" data-cy="categories-list" class="css-jfja6s">
        <li data-cy="cy-im-parent" class="css-xedlmo">
        <div class="css-17fti8"><span>
            <p class="css-1jek2ew-Text eu5v0x0">Some Unique Text 1</p></span>
            <span font-size="p4" class="css-my4n3k"></span>
        </div>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" class="css-1mougrc">
            </svg></li><li data-cy="cy-im-parent" class="css-xedlmo">
        <div class="css-17fti8"><span><p class="css-1jek2ew-Text eu5v0x0">Some Unique Text 2</p></span>
            <span font-size="p4" class="css-my4n3k"></span></div>
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" class="css-1mougrc">
            </svg></li>
        <li data-cy="cy-im-child" data-testid="nested-category-item" class="css-12lzvy8">
        <div class="css-19rredd">
        <section class="css-u2ayx9">
            <p class="css-1jek2ew-Text eu5v0x0">Some Unique Text 3</p>
        </section>
        <span font-size="p4" class="css-6zq905"></span></div></li>
        <li data-cy="cy-im-parent" class="css-xedlmo">
            <div class="css-17fti8"><span><p class="css-1jek2ew-Text eu5v0x0">Some Unique Text 4</p></span>
            <span font-size="p4" class="css-my4n3k"></span></div><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" class="css-1mougrc">
            </li><li data-cy="cy-im-child" data-testid="nested-category-item" class="css-12lzvy8">
        <div class="css-19rredd">
        <section class="css-u2ayx9">
            <p class="css-1jek2ew-Text eu5v0x0">Some Unique Text 5</p>
        </section>
    <span font-size="p4" class="css-6zq905"></span></div></li></ul>
</section>

Any idea?


Solution

  • You can try this if you only want to click on one paragraph element containing specific text.

    await page.evaluate(() => {
      const elements = [...document.querySelectorAll('p')];
      const targetElement = elements.find(e => e.innerText == 'Some Unique Text 3');
      if (targetElement) targetElement.click();
    });
    

    Or if you want to click on multiple paragraph elements containing specific text try this.

    await page.evaluate(() => {
      Array.from(document.querySelectorAll('p')).filter(p => {
        return p.innerText == 'Some Unique Text 3'
      }).forEach(element => {
        if (element) element.click();
      });
    });