Showing posts with label Playwright Dropdowns. Show all posts
Showing posts with label Playwright Dropdowns. Show all posts

Count Multiple Elements in Dropdown in Playwright

















Dropdown in Playwright: How to Count Multiple Elements in a Dropdown

Dropdowns are one of the most common UI elements in modern web applications. Whether you are selecting a country, choosing a payment method, filtering products, or selecting user roles, dropdowns play a crucial role in user interaction.

When working with Playwright, automation engineers often need not only to select values from dropdowns but also to count how many options are available inside them. This becomes especially important in validation testing, dynamic content verification, and data-driven automation.

In this detailed, SEO-optimized, AdSense-friendly guide, you will learn:

  • What is a dropdown in Playwright?

  • Types of dropdowns in web applications

  • How to locate dropdown elements

  • How to count multiple elements in a dropdown

  • Real-world testing use cases

  • Complete Java code example

  • Best practices for handling dropdowns in Playwright

This article is written in a clear, human-like style so that beginners and experienced automation testers can understand and implement it easily.


What is a Dropdown in Playwright?

A dropdown is typically represented in HTML using:

<select> <option>Option 1</option> <option>Option 2</option> </select>

However, modern web applications often use custom dropdowns built with:

  • <div>

  • <li>

  • <ul>

  • <span>

From Playwright’s perspective, a dropdown is simply a collection of elements that can be located and interacted with using Locators.


Types of Dropdowns in Web Applications

Understanding dropdown types is important before automating them.

1. Standard HTML Dropdown (<select>)

  • Uses <select> and <option> tags

  • Easy to automate

  • Supports built-in selection methods

2. Custom Dropdown

  • Built using <div> or <li>

  • Often styled with JavaScript frameworks

  • Requires clicking to expand before selecting options

3. Dynamic Dropdown

  • Options change based on user input

  • Example: Selecting country loads states dynamically

Each type requires slightly different automation strategies.


Why Count Dropdown Options in Automation Testing?

Many beginners only focus on selecting dropdown values. However, counting dropdown options is equally important.

Here’s why:

1. Validation Testing

Ensure the dropdown contains the expected number of items.

Example:

  • Country dropdown should contain 195 countries.

  • Month dropdown should contain 12 months.


2. Dynamic Dropdown Verification

If selecting “India” loads 28 states, your automation must verify:

  • Correct number of states loaded

  • No missing or duplicate entries


3. Data Integrity Testing

Ensure:

  • No duplicate options exist

  • No blank values are present

  • Required options are available


4. Regression Testing

When UI changes occur, dropdown options may accidentally be removed or duplicated. Counting ensures UI consistency.


Steps to Count Multiple Elements in a Dropdown Using Playwright

Let’s break it down into simple steps.


Step 1: Locate the Dropdown

First, identify the dropdown element using a Locator.

Example:

page.locator("#dropdown-class-example");


Step 2: Identify Dropdown Options

For <select> dropdowns:

  • Options are <option> elements.

For custom dropdowns:

  • Options may be <li> or <div> elements.


Step 3: Retrieve All Matching Elements

Use Playwright’s locator to capture all child elements.


Step 4: Count the Elements

Use:

locator.count();

This returns the total number of matching elements.


Step 5: Validate and Use in Test

You can:

  • Assert expected count

  • Print each option text

  • Validate dropdown data


Example Website for Practice

We will use:

Rahul Shetty Academy Automation Practice

URL:
https://rahulshettyacademy.com/AutomationPractice/

This site contains a sample dropdown perfect for automation practice.


Complete Java Code Example: Count Dropdown Options

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 dropdown options Locator dropdownOptions = page.locator("#dropdown-class-example option"); // Count 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(); } } }


Detailed Code Explanation

Let’s understand this step-by-step.


1. Launch the Browser

Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false));
  • Launches Chromium browser

  • Headless false allows visual execution


2. Create BrowserContext

BrowserContext context = browser.newContext();

Creates a fresh session.


3. Navigate to Website

page.navigate("https://rahulshettyacademy.com/AutomationPractice/");

Opens practice website.


4. Locate Dropdown Options

Locator dropdownOptions = page.locator("#dropdown-class-example option");

Important correction:

We use option to target individual dropdown options.


5. Count Elements

int optionCount = dropdownOptions.count();

Returns total number of <option> elements.


6. Print Each Option

dropdownOptions.nth(i).textContent();

Fetches text of each dropdown option.


Handling Custom Dropdowns

For custom dropdowns:

Example HTML:

<ul> <li>Option 1</li> <li>Option 2</li> </ul>

You must:

  1. Click dropdown to expand

  2. Locate <li> elements

  3. Count them

Example:

page.locator("#customDropdown").click(); Locator options = page.locator("//ul/li"); int count = options.count();


Validating Dropdown Count with Assertion (TestNG Example)

If using TestNG:

Assert.assertEquals(optionCount, 3, "Dropdown count mismatch!");

This ensures expected number of options.


Real-World Automation Scenarios

E-Commerce Platform

  • Verify category dropdown contains expected product categories.

  • Ensure no duplicate category entries.


Banking Application

  • Validate account type dropdown contains:

    • Savings

    • Current

    • Fixed Deposit


Government Portal

  • Verify state list updates based on country selection.


Best Practices for Dropdown Automation

  1. Always target specific child elements (like option).

  2. Avoid using overly generic locators.

  3. Validate both count and content.

  4. Handle dynamic loading properly.

  5. Wait for dropdown to be visible before counting.

  6. Use Page Object Model for better maintainability.


Common Mistakes to Avoid

  • Counting the dropdown container instead of options.

  • Not expanding custom dropdown before counting.

  • Ignoring dynamic content loading.

  • Not validating option text.


Advantages of Using Playwright for Dropdown Handling

  • Powerful Locator API

  • Built-in waiting mechanisms

  • Supports dynamic content

  • Cross-browser testing capability

  • Fast execution


SEO Keywords Covered

  • Dropdown in Playwright

  • Count dropdown options in Playwright Java

  • Playwright locator count method

  • Handle dropdown in Playwright

  • Playwright automation tutorial

  • Playwright Java example

  • Count multiple elements Playwright

  • Dropdown validation in automation


Suggested Posts:

1. Handle IFrames in Playwright
2. Automate Login Page in Playwright
3. Comma Selectors in Playwright
4. Handle Alerts in Playwright
5. Page Object Model in Playwright

Handling Dropdowns in Playwright




Complete Guide to Handling Dropdowns in Playwright Java (SEO Optimized & AdSense Friendly)

Dropdowns are one of the most commonly used user interface elements in web applications. Whether you are filling out a registration form, selecting a country, choosing a payment method, or applying filters in an e-commerce application, dropdown menus are everywhere.

For automation testers and developers working with Playwright, understanding how to handle dropdowns efficiently is extremely important. In this detailed and beginner-friendly guide, we will explore everything you need to know about dropdown handling in Playwright Java.

This article covers:

  • What is a dropdown (select box)?

  • Types of dropdowns in web applications

  • Dropdowns in Playwright automation

  • Challenges while handling dropdowns

  • Handling HTML <select> dropdowns in Playwright Java

  • Handling custom or dynamic dropdowns

  • Best practices for dropdown automation

  • Common interview questions related to dropdown handling

This guide is written in a human-friendly style and optimized for SEO and AdSense compliance.


What Is a Dropdown?

A dropdown (also called a select box) is a user interface element that allows users to choose one or sometimes multiple options from a predefined list.

In standard HTML, dropdowns are typically created using:

  • <select> tag

  • <option> tags inside it


Example of Standard HTML Dropdown

<select id="dropdown">
  <option value="option1">Java</option>
  <option value="option2">Python</option>
  <option value="option3">JavaScript</option>
</select>

In this example:

  • <select> creates the dropdown.

  • <option> defines each selectable value.

However, modern web applications often use custom dropdowns built using:

  • <div>

  • <ul>

  • <li>

  • JavaScript frameworks like React or Angular

These are called custom or dynamic dropdowns.


Dropdowns in Playwright Context

When working with Playwright automation, dropdown handling means:

  • Selecting an option

  • Verifying selected value

  • Handling dynamic dropdown behavior

  • Managing dependent dropdowns (e.g., Country → State)

Dropdown testing ensures that:

  • All options are displayed correctly

  • The correct value can be selected

  • Application behavior changes appropriately after selection


Types of Dropdowns in Playwright

There are mainly two types of dropdowns that automation testers encounter.


1. Standard HTML Dropdown (Native Select Menu)

These dropdowns:

  • Use <select> and <option>

  • Follow standard HTML structure

  • Are easy to automate

  • Are directly supported by Playwright’s selectOption() method

These are the simplest type to handle.


2. Custom / Dynamic Dropdown (Non-Standard)

These dropdowns:

  • Are built using <div>, <span>, <ul>, <li>

  • Often styled using Bootstrap, Material UI, or other frameworks

  • May hide options until clicked

  • Require click-based interaction

These require more careful handling.


Why Dropdown Handling Is Important in Automation Testing

Dropdowns are used in:

  • Registration forms

  • Country and state selection

  • Payment forms

  • Search filters

  • Settings panels

  • Dashboard configurations

Testing dropdown functionality ensures:

  • Correct options are available

  • No incorrect or duplicate options appear

  • Dependent dropdowns update properly

  • UI reacts correctly to selection changes

For example:
Selecting "India" should load Indian states in the next dropdown.


Challenges with Dropdowns in Playwright

Automation testers may face the following challenges:


1. Dynamic Loading

Some dropdown options appear only after clicking or after an API call.

Solution:
Use proper waiting mechanisms like:

page.waitForSelector()


2. Hidden Elements

Some frameworks hide the actual <select> and use a styled <div> instead.

Solution:
Inspect DOM carefully using browser DevTools.


3. Multiple Selection Dropdowns

Some dropdowns allow selecting multiple options.

Example:

<select multiple>

Playwright supports this using an array in selectOption().


4. Asynchronous Behavior

Selecting an option may trigger:

  • AJAX calls

  • Page reload

  • DOM updates

Solution:
Use proper synchronization like:

page.waitForLoadState();


1. Handling HTML <select> Dropdown in Playwright Java

If the dropdown is built using <select> and <option>, Playwright provides the selectOption() method.


Example HTML

<select id="dropdown-class-example"> <option value="option1">Java</option> <option value="option2">Python</option> <option value="option3">JavaScript</option> </select>


Playwright Java Code Example

import com.microsoft.playwright.*; public class DropdownSelectExample { public static void main(String[] args) throws InterruptedException { try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); Page page = browser.newPage(); // Navigate to page page.navigate("https://rahulshettyacademy.com/AutomationPractice/"); // Select option by value page.locator("#dropdown-class-example").selectOption("option2"); // Pause execution for demo Thread.sleep(2000); System.out.println("Option selected."); browser.close(); } } }


Step-by-Step Code Explanation

(a) Navigate to URL

page.navigate()

Opens the webpage containing dropdown.


(b) Locate Dropdown

page.locator("#dropdown-class-example")

Finds dropdown using ID.


(c) Select Option

.selectOption("option2")

Selects option by value.


Other Ways to Select Option

You can also select by:

Select by Visible Text

selectOption(new SelectOption().setLabel("Python"));

Select by Index

selectOption(new SelectOption().setIndex(2));


2. Handling Custom Dropdown (Div-Based or Dynamic)

Custom dropdowns are not built using <select> tag. They require:

  1. Clicking dropdown

  2. Clicking option


Example Website

https://seleniumpractise.blogspot.com/2016/08/bootstrap-dropdown-example-for-selenium.html#


Playwright Java Code Example

import com.microsoft.playwright.*; public class CustomDropdownExample { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); Page page = browser.newPage(); page.navigate("https://seleniumpractise.blogspot.com/2016/08/bootstrap-dropdown-example-for-selenium.html#"); // Scroll if needed page.locator("#menu1").scrollIntoViewIfNeeded(); // Click dropdown page.locator("#menu1").click(); // Click first option page.locator("ul[class='dropdown-menu']>li:nth-child(1)>a").click(); System.out.println("Custom option selected."); browser.close(); } } }


Step-by-Step Explanation

(a) Navigate to URL

page.navigate()


(b) Scroll into View

scrollIntoViewIfNeeded()

Ensures dropdown is visible.


(c) Click Dropdown

page.locator("#menu1").click();


(d) Click Option

page.locator("ul[class='dropdown-menu']>li:nth-child(1)>a").click();

Selects first option.


Handling Multiple Selection Dropdown

If dropdown supports multiple selections:

page.locator("#multi-select") .selectOption(new String[]{"option1", "option3"});


Verifying Selected Option

You can verify selected value:

String selected = page.locator("#dropdown").inputValue(); System.out.println("Selected: " + selected);


Best Practices for Dropdown Handling in Playwright

✔ Prefer ID or unique attributes for locating dropdown
✔ Avoid fragile CSS selectors like nth-child()
✔ Use explicit waits for dynamic dropdowns
✔ Inspect DOM carefully before writing locator
✔ Handle dependent dropdown scenarios properly
✔ Use Page Object Model (POM) for maintainable code


Real-World Example: Dependent Dropdown

Example:

  • Select Country

  • State dropdown updates dynamically

In such cases:

page.locator("#country").selectOption("India"); page.waitForSelector("#state option[value='Karnataka']"); page.locator("#state").selectOption("Karnataka");

Synchronization is critical.


Common Interview Questions on Dropdown Handling

  1. How do you handle dropdown in Playwright?

  2. Difference between standard and custom dropdown?

  3. How to select multiple options?

  4. How to handle dynamic dropdowns?

  5. How to verify selected value?


Common Mistakes to Avoid

❌ Using Thread.sleep excessively
❌ Using fragile XPath with indexes
❌ Ignoring asynchronous behavior
❌ Not verifying selection


Advanced Tip: Use getByRole for Better Stability

Playwright recommends:

page.getByRole(AriaRole.COMBOBOX).selectOption("option2");

This improves accessibility-based automation.


Conclusion

Dropdown handling is a fundamental skill in automation testing with Playwright Java. Whether it is a simple HTML <select> dropdown or a complex dynamic React-based dropdown, understanding how to interact with it correctly ensures reliable test automation.

Standard dropdowns are easy to automate using selectOption(), while custom dropdowns require click-based interactions. Always inspect the DOM carefully and use stable locators.

Mastering dropdown handling will help you build robust automation frameworks and perform better in automation testing interviews.

If you are learning Playwright, make sure to practice both standard and custom dropdown scenarios.