×
☰ See All Chapters

Attribute Selector in Puppeteer

Attribute selector is used when we have an attribute used only once in a tag. The standard syntax for attribute selector expression is

tagName[attributeName='attributeValue']

If puppeteer identifies more than one matching element, then the first matching element will be located.

Attribute Selector in Puppeteer Example:

Following are the 4 different ways of writing attribute selector expression for below mentioned input tag

<input type=“text” id=“testID” class=“inputText” value= “firstName” >

  1. input[type='text'] 

  2. input[id='testID'] 

  3. input[class='inputText'] 

  4. input[value='firstName'] 

While deriving attribute selector expression, we can use either one attribute or multiple attributes till we found unique matching element on the web page.

e.g.: input[type=’text’][id=’testID’][class=’inputText’][value=’firstName’]

selector.ts

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/selenium/testpages/registration-form-testpage');

    await enterLastName(page);

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

    await wait(5000);

   

    //Close browser

    await browser.close();

}

//Attribute selector

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

    const lastName = await page.$("input[name='lastname']");

    //we can use either one attribute or multiple attributes till we found unique matching element on the web page.

    //const lastName = await page.$("input[name='lastname'][type='text']");

    await lastName.focus();

    await lastName.type("Manjunatha");

}

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

You can write the script and test above example using our below Test Page

attribute-selector-in-puppeteer-0
 

All Chapters
Author