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

Open a New Tab in Playwright




















How to Open and Manage Multiple Tabs in Playwright Java

Modern web applications frequently use multiple browser tabs to enhance user experience. From payment gateways and authentication redirects to product comparisons and social media feeds, multi-tab workflows are common in real-world applications.

If you are working with Playwright in Java, understanding how to open and manage tabs properly is essential for building stable and scalable automation frameworks.

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

  • What is a tab in Playwright?

  • How Playwright represents browser tabs

  • How to open a new tab in Playwright Java

  • How to switch between multiple tabs

  • How to close tabs safely

  • Real-world testing use cases

  • Best practices for handling multi-tab scenarios

This guide is written in a simple, human-like explanation style so that beginners and experienced automation engineers can both benefit.


What is a Tab in Playwright?

In browser automation, a tab is represented as a Page object in Playwright.

In simple terms:

Each browser tab = One Page object in Playwright.

When you create a new Page instance inside a BrowserContext, Playwright opens a new tab in the same browser window.

However, all tabs created under the same BrowserContext share:

  • Cookies

  • Local storage

  • Session storage

  • Authentication state

Unless you create separate BrowserContexts, tabs under the same context behave like tabs inside a normal browser window.


Understanding Browser, Context, and Page in Playwright

To understand tabs properly, you must understand Playwright’s architecture.

1. Browser

The browser represents the actual browser engine (Chromium, Firefox, WebKit).

2. BrowserContext

A BrowserContext behaves like an incognito window. It isolates session data.

3. Page

A Page represents a single tab inside a BrowserContext.

So the structure looks like:

Browser → BrowserContext → Page (Tab 1) → Page (Tab 2) → Page (Tab 3)

This architecture makes Playwright extremely powerful for handling multiple tabs.


Why Multiple Tabs Are Important in Automation Testing

Many real-world applications require multi-tab workflows.

Some common scenarios include:

1. E-commerce Applications

  • Open product page in one tab

  • Open cart in another tab

  • Compare products across tabs

2. Authentication Testing

  • Login in first tab

  • Open secure dashboard in second tab

  • Verify session sharing

3. Payment Gateway Redirection

  • Click “Pay Now”

  • New tab opens for payment provider

  • Validate payment page content

4. Social Media Platforms

  • Open feed in one tab

  • Open profile in another tab

  • Compare user interactions

Handling such scenarios properly improves test coverage and reliability.


How to Open a New Tab in Playwright Java

Opening a new tab in Playwright Java is very simple.

You just create a new Page inside the same BrowserContext.

Let’s understand step-by-step.


Step-by-Step Process to Open Multiple Tabs

Step 1: Launch the Browser

First, launch the browser using Playwright.

Step 2: Create a BrowserContext

Create a new BrowserContext using:

browser.newContext()

This represents a user session.

Step 3: Open First Tab

Create a Page:

context.newPage()

This opens the first tab.

Step 4: Open Second Tab

Call context.newPage() again.

Each call opens a new tab.

Step 5: Perform Actions on Each Tab

You can navigate to different websites and perform actions independently.


Example Websites Used

We will use:

Example.com
Playwright


Java Code to Open Multiple Tabs in Playwright

Below is a complete working example:

import com.microsoft.playwright.*; public class OpenNewTabExample { public static void main(String[] args) { try (Playwright playwright = Playwright.create()) { // Step 1: Launch browser Browser browser = playwright.chromium() .launch(new BrowserType.LaunchOptions().setHeadless(false)); // Step 2: Create a new browser context BrowserContext context = browser.newContext(); // Step 3: Open the first tab Page firstTab = context.newPage(); firstTab.navigate("https://example.com"); System.out.println("First tab title: " + firstTab.title()); // Step 4: Open second tab Page secondTab = context.newPage(); secondTab.navigate("https://playwright.dev"); System.out.println("Second tab title: " + secondTab.title()); // Wait for visibility before closing Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } } }


Code Explanation in Detail

Let’s break it down clearly.


(a) Launch the Browser

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

  • setHeadless(false) opens browser in visible mode


(b) Create BrowserContext

BrowserContext context = browser.newContext();
  • Represents a new user session

  • Works like an incognito window


(c) Open First Tab

Page firstTab = context.newPage(); firstTab.navigate("https://example.com");
  • newPage() creates a new tab

  • navigate() loads the website


(d) Open Second Tab

Page secondTab = context.newPage(); secondTab.navigate("https://playwright.dev");
  • Another tab is created

  • Different website is loaded


(e) Wait Time

Thread.sleep(5000);

This allows you to visually see the browser tabs before execution ends.


Switching Between Tabs in Playwright

Since each tab is stored in a different Page object, switching is simple.

Example:

firstTab.bringToFront(); secondTab.bringToFront();

You can interact with any tab at any time using its Page reference.


Running Multiple Tabs in Parallel

Playwright supports multiple Page instances simultaneously.

You can:

  • Navigate tabs independently

  • Perform form filling in one tab

  • Click buttons in another tab

  • Validate titles and elements across tabs

This makes it powerful for advanced testing scenarios.


Closing Tabs Independently

If a tab is no longer needed:

firstTab.close();

This will close only that tab.

Other tabs remain open.

Closing tabs independently helps manage memory and maintain clean test execution.


Important Concepts to Remember

1. BrowserContext Behavior

BrowserContext behaves like an incognito window.

Tabs under the same context:

  • Share cookies

  • Share session storage

  • Share authentication

If you want full isolation, create a new BrowserContext.


2. Each Page = One Tab

Calling context.newPage() always creates a new tab.


3. Session Sharing

Tabs under same context can share login state.

Example:

  • Login in first tab

  • Open dashboard in second tab

  • Session remains active


Advanced Scenario: Handling Tab Opened by Clicking a Link

Sometimes clicking a link opens a new tab automatically.

Example:

Page newTab = context.waitForPage(() -> { firstTab.click("a[target='_blank']"); });

This ensures Playwright waits for the new tab to open.


Real-World Testing Scenarios

E-Commerce Application

  • Open product details in one tab

  • Open comparison page in another tab

  • Validate product price consistency

Banking Application

  • Login in one tab

  • Open transaction history in another tab

  • Validate session persistence

SaaS Dashboard

  • Open analytics in first tab

  • Open settings in second tab

  • Validate user data consistency


Best Practices for Handling Multiple Tabs

  1. Always store Page references clearly.

  2. Avoid using global Page variables.

  3. Close unused tabs to free resources.

  4. Use BrowserContext properly for session control.

  5. Use waitForPage when handling popup tabs.


Common Mistakes to Avoid

  • Forgetting to handle popup tabs

  • Using wrong Page reference

  • Closing Browser before closing Page

  • Not waiting for tab to load before interaction


Benefits of Multi-Tab Testing in Playwright

  • Realistic user simulation

  • Better workflow validation

  • Improved test coverage

  • Enhanced reliability

  • Supports complex applications


SEO Keywords Covered

  • Open new tab in Playwright Java

  • Playwright multiple tabs example

  • Playwright Page object

  • BrowserContext in Playwright

  • Switch tabs in Playwright Java

  • Playwright multi-tab automation

  • Handle new tab in Playwright

  • Playwright Java tutorial



Suggested Posts:

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