×
☰ See All Chapters

ID Selector in Puppeteer

According to World Wide Web Consortium (W3C) ID’s are unique for each element so it is easy way to locate elements using ID selector. ID selectors are the fastest out of all selectors. Many say that ID selectors are safest selectors, this is not true, because developers may use duplicate ID’s and as browsers do allow bypassing W3C rule. While populating list and tables developers sometimes use same ID’s for all the items in list.

Syntax

Example

#value of id attribute

#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 enterFirstName(page);

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

    await wait(5000);

    //Close browser

    await browser.close();

}

//id selector

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

    const firtName = await page.$("#firstname");

    await firtName.focus();

    await firtName.type("Manu");

}

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

id-selector-in-puppeteer-0
 

All Chapters
Author