Count Multiple Elements in Dropdown in Playwright

 

To count multiple elements in a dropdown using Playwright Java, you need to:












Steps:

  • Launch the browser.
  • Navigate to a web page with a dropdown (e.g., https://demoqa.com/select-menu).
  • Locate the dropdown element.
  • Get all options inside the dropdown using a locator.
  • Count the number of options.


Example Website:

We’ll use: https://demoqa.com/select-menu

There is a dropdown with the id: oldSelectMenu.



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://demoqa.com/select-menu");

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

            // 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();
        }
    }
}



No comments:

Post a Comment