Count Multiple Elements in Dropdown in Playwright

 



Dropdown in Playwright

A dropdown is usually represented in HTML using a <select> tag with multiple <option> elements, or sometimes as a custom dropdown built with <div> or <li> elements.

When working with dropdowns in automation, sometimes you don’t just want to select an option, but also count how many options are present.


Counting Multiple Elements in a Dropdown in Playwright

(1) Locate the Dropdown

  • First, you need to identify the dropdown element (e.g., <select> or custom dropdown).
  • In Playwright, we interact with it using a Locator.


(2) Identify Dropdown Options

  • Inside the dropdown, multiple child elements represent available options. For <select>, these are <option> elements. For custom dropdowns, it could be <li>, <div>, or any repeated tag structure.

(3) Retrieve All Options

  • Using Playwright, you can fetch all the matching elements (for example, all <option> tags inside the dropdown).
  • This gives you a list/collection of elements.

(4) Count the Elements

  • Once you have the collection, you can count how many elements are present.
  • This tells you the total number of items in the dropdown.

(5) Use Cases in Testing

  • Validation: Verify the dropdown has the expected number of options.
  • Dynamic dropdowns: Check if the options are loading correctly (e.g., states list changes when you pick a country).
  • Data-driven testing: Ensure that no option is missing or duplicated.










Example Website:

We’ll use: https://rahulshettyacademy.com/AutomationPractice/






Code in Playwright Java:

import com.microsoft.playwright.*;

public class DropdownCountExample {
    public static void main(String[] args) {
        try (Playwright playwright = Playwright.create()) {
            Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
            BrowserContext context = browser.newContext();
            Page page = context.newPage();

            // Navigate to demo site
            page.navigate("https://rahulshettyacademy.com/AutomationPractice/");

            // Locate the dropdown and get all option elements
            Locator dropdownOptions = page.locator("#dropdown-class-example");

            // Count the number of dropdown options
            int optionCount = dropdownOptions.count();
            System.out.println("Total options in dropdown: " + optionCount);

            // Print each option text
            for (int i = 0; i < optionCount; i++) {
                System.out.println("Option " + (i + 1) + ": " + dropdownOptions.nth(i).textContent());
            }

            browser.close();
        }
    }
}

Code explanation:


Code for count multiple elements: