How to click on element with text in Puppeteer

后端 未结 9 1167
灰色年华
灰色年华 2020-11-27 12:53

Is there any method (didn\'t find in API) or solution to click on element with text?

For example I have html:

相关标签:
9条回答
  • 2020-11-27 12:55

    The solution is

    (await page.$$eval(selector, a => a
                .filter(a => a.textContent === 'target text')
    ))[0].click()
    
    0 讨论(0)
  • 2020-11-27 12:56

    There is no supported css selector syntax for text selector or a combinator option, my work around for this would be:

    await page.$$eval('selector', selectorMatched => {
        for(i in selectorMatched)
          if(selectorMatched[i].textContent === 'text string'){
              selectorMatched[i].click();
              break;//Remove this line (break statement) if you want to click on all matched elements otherwise the first element only is clicked  
            }
        });
    
    0 讨论(0)
  • 2020-11-27 12:58

    made quick solution to be able to use advanced css selectors like ":contains(text)"

    so using this library you can just

    const select = require ('puppeteer-select');
    
    const element = await select(page).getElement('button:contains(Button text)');
    await element.click()
    
    0 讨论(0)
  • 2020-11-27 13:00

    There are many answers suggesting contains but I don't see any motivation for this imprecision given OP's use case which, by all appearances, is an exact match with a target string of "Button text" and an element <button>Button text</button>.

    I'd prefer to use the more precise [text()="Button text"], which avoids a false positive when the button is, say, <button>Button text and more stuff</button>:

    const [el] = await page.$x('//*[@class="elements"]//a[text()="Button text"]');
    el && (await el.click());
    

    This anticipates the opposite scenario of this answer which attempts to be as permissive as possible.

    Many answers also missed the .elements parent class requirement.

    0 讨论(0)
  • 2020-11-27 13:05

    Here is my solution:

    let selector = 'a';
        await page.$$eval(selector, anchors => {
            anchors.map(anchor => {
                if(anchor.textContent == 'target text') {
                    anchor.click();
                    return
                }
            })
        });
    
    0 讨论(0)
  • 2020-11-27 13:07

    I had to:

    await this.page.$eval(this.menuSelector, elem => elem.click());

    0 讨论(0)
提交回复
热议问题