×
☰ See All Chapters

Class Selector in Puppeteer

Class selector helps in locating element defined through the class attribute. Most of the times same css class will be used for many elements. If in case class is used only with one element, it can be used for class locator. If Multiple elements on the web page have same class, in such case puppeteer always locates the first matching element.

Syntax

Example

.value of class attribute

.datePicker

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

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

    await wait(5000);

    //Close browser

    await browser.close();

}

 

//Class selector  

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

    const dob = await page.$(".datePicker");

    await dob.focus();

    await dob.type("01-01-2020");

}

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

class-selector-in-puppeteer-0
 

All Chapters
Author