×
☰ See All Chapters

Puppeteer relative xpath using contains function

In the html code of an element, if the attribute value or the text is changing partially, then use contains() function to identify the element.  In order to use contains() function, the element should have either attribute value or text value. We use contains() function when the text value is very lengthy or the attribute value is very lengthy.

Syntax:

//tagname[contains(@attributeName,'attributeValue')]

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

Few examples for relative xpath using contains() function for the below sample html code

<html>

</head>

<body>

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

        <tr>

                <td>Row 1 : </td>

                <td><input type="text" id="xyz"></td>

        </tr>

        <tr>

                <td>Row 2 : </td>

                <td><input type="text" name="lmn"></td>

        </tr>

        <tr>

                <td>Row 3 : </td>

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

        </tr>

        <tr>

                <td>Row 4 : </td>  

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

        </tr>

</table>

</body>

</html>

 

Relative xpath expressions using contains ()

 Matching Element

//input[contains(@id,'xyz')]

Row 1 Input

//input[contains(@name,'lmn')]

Row 2 Input

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

Row 3 Button

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

Row 4 Button

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

puppeteer-relative-xpath-using-contains-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("//input[contains(@id,'xyz')]"))[0];

    element.type("www.tools4testing.com");

}

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