How to click on element with text in Puppeteer

后端 未结 9 1231
灰色年华
灰色年华 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:18

    You may use a XPath selector with page.$x(expression):

    const linkHandlers = await page.$x("//a[contains(text(), 'Some text')]");
    
    if (linkHandlers.length > 0) {
      await linkHandlers[0].click();
    } else {
      throw new Error("Link not found");
    }
    

    Check out clickByText in this gist for a complete example. It takes care of escaping quotes, which is a bit tricky with XPath expressions.

提交回复
热议问题