How to click on element with text in Puppeteer

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

    The current top answer by tokland only works on text nodes and not on nodes with other elements inside.

    Short answer

    This XPath expression will query a button which contains the text "Button text":

    const [button] = await page.$x("//button[contains(., 'Button text')]");
    if (button) {
        await button.click();
    }
    

    To also respect the

    surrounding the buttons, use the following code:

    const [button] = await page.$x("//div[@class='elements']/button[contains(., 'Button text')]");
    

    Explanation

    To explain why using the text node (text()) is wrong in some cases, let's look at an example:

    First, let's check the results when using contains(text(), 'Text'):

    • //button[contains(text(), 'Start')] will return both two nodes (as expected)
    • //button[contains(text(), 'End')] will only return one nodes (the first) as text() returns a list with two texts (Start and End), but contains will only check the first one
    • //button[contains(text(), 'Middle')] will return no results as text() does not include the text of child nodes

    Here are the XPath expressions for contains(., 'Text'), which works on the element itself including its child nodes:

    • //button[contains(., 'Start')] will return both two buttons
    • //button[contains(., 'End')] will again return both two buttons
    • //button[contains(., 'Middle')] will return one (the last button)

    So in most cases, it makes more sense to use the . instead of text() in an XPath expression.

提交回复
热议问题