How to click on element with text in Puppeteer

后端 未结 9 1217
灰色年华
灰色年华 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 13:20

    You can also use page.evaluate() to click elements obtained from document.querySelectorAll() that have been filtered by text content:

    await page.evaluate(() => {
      [...document.querySelectorAll('.elements button')].find(element => element.textContent === 'Button text').click();
    });
    

    Alternatively, you can use page.evaluate() to click an element based on its text content using document.evaluate() and a corresponding XPath expression:

    await page.evaluate(() => {
      const xpath = '//*[@class="elements"]//button[contains(text(), "Button text")]';
      const result = document.evaluate(xpath, document, null, XPathResult.ANY_TYPE, null);
    
      result.iterateNext().click();
    });
    

提交回复
热议问题