×
☰ See All Chapters

Selenium relative xpath using starts with function

We use starts-with() function to identify those elements whose text value  starts with some specified value.

Syntax:

//tagname[starts-with(text(),'text value of the tag')]

Comparison between contains() and starts-with() functions considering below sample html code

<html>

</head>

<body>

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

        <tr>

                <td>Row 1 : </td>

                <td><span>welcome to www.tools4testing.com</span></td>

        </tr>

        <tr>

                <td>Row 2 : </td>

                <td><span>you are welcome !</span></td>

        </tr>

</table>

</body>

</html>

 

Relative xpath

 Matching Element

//span[starts-with(text(),'welcome')]

Row 1 Span

//span[contains(text(),'welcome')]

Both Row1 and Row 2 Span

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

puppeteer-relative-xpath-using-starts-with-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-contains-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 element = (await page.$x("//span[contains(text(),'welcome')]"))[0];

    element.click();

}

 

//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