×
☰ See All Chapters

Puppeteer relative xpath using text function

In the html code of an element, if attribute is duplicate or attribute itself is not present,  then use text() function to identify the element. In order to use text() function, the element should have text in the element’s html code.

Syntax:

//tagname[text()='text value of the tag']

                                OR

//tagname[.='text value of the tag']

Instead of text(), we can use dot (.) , the problem here with using dot (.) is sometimes, it returns the hidden element also present on the webpage. which might confuse the user. So the best practice is to use text() instead of using dot.

Few examples for relative xpath using text() for the below sample html code:

<html>

</head>

<body>

<table align="center" width=90% cellspacing="2" cellpadding="2" >

        <tr>

                <td><button type="button">www.tools4testing.com</button></td>  

                <td><button type="button">www.java4coding.com</button></td>  

        </tr>

</table>

</body>

</html>

 

//button[text()='www.tools4testing.com']

Selects button with the text www.tools4testing.com

//button[text()='www.java4coding.com']

Selects button with the text www.java4coding.com

You can write the script and test these using our Test Page

puppeteer-relative-xpath-using-text-function-0
 

import { launch, Page } from 'puppeteer';

 

example();

async function example() {

    const browser = await launch({headless : false});

    const page = await browser.newPage();

    await page.setViewport({ width: 1366, height: 768});

    await page.goto('https://www.tools4testing.com/contents/puppeteer/testpages/puppeteer-relative-xpath-by-text-function-testpage');

    await testXpath(page);

    //wait for some time before closing, specify time in milliseconds

    await wait(5000);

    //Close browser

    await browser.close();

}

 

async function testXpath(page: Page) : Promise<void> {

    const element1 = (await page.$x("//button[text()='www.tools4testing.com']"))[0];

    element1.click();

    page.on('dialog', async dialog => {

        console.log(dialog.message());

        await dialog.accept();

    });

    const element2 = (await page.$x("//button[text()='www.java4coding.com']"))[0];

    element2.click();

    page.on('dialog', async dialog => {

        console.log(dialog.message());

        await dialog.accept();

    });

}

//wait if needed

async function wait(time) {

    return new Promise(function(resolve) {

        setTimeout(resolve, time)

    });

}

Click here to learn to execute puppeteer example using typescript

 


All Chapters
Author