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

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:




Handling Dropdowns in Playwright

 



A dropdown (also called a select box) is a user interface element that allows a user to choose one (or sometimes multiple) options from a predefined list. In HTML, dropdowns are typically represented by the <select> element containing <option> tags, or they can be custom-built using <div>, <ul>, or JavaScript frameworks.


Dropdowns in Playwright Context

When automating with Playwright, dropdown handling means interacting with these elements to select values, verify selected options, or test behavior when selections change.


Types of Dropdowns in Playwright

Standard HTML Dropdowns (Native Select Menus):

  • Built using <select> and <option>.
  • Easy to interact with because they follow HTML standards.
  • Playwright recognizes them directly as form elements.

Custom / Dynamic Dropdowns (Non-Standard):

  • Created using <div>, <li>, or JavaScript-based UI libraries
  • Options might be hidden in the DOM until the dropdown is clicked.
  • Require more interaction (like clicking to expand, then choosing an item).


Why Dropdown Handling is Important

  • Dropdowns are commonly used for forms, filters, country/state selectors, and settings menus.
  • Testing dropdowns ensures that the correct options appear, can be selected, and that the application reacts appropriately to user choices.
  • It also validates dynamic behavior, such as when choosing one option updates another dropdown (e.g., country → state selection).
  • Handling a dropdown in Playwright Java can be done in different ways depending on the type of dropdown:

Challenges with Dropdowns in Playwright
  • Dynamic loading: Options may not be present in the DOM until the dropdown is clicked.
  • Hidden elements: Some frameworks hide the real <select> and use a styled <div> or <span>.
  • Multiple selections: Some dropdowns allow multiple options, requiring special handling.
  • Asynchronous behavior: Selecting an option may trigger AJAX requests or page updates, so synchronization (waiting) is crucial.



1. HTML <select> Tag Dropdown

If the dropdown is built using the standard <select> tag, you can use the selectOption() method.


2. Custom Dropdown (Div-based or React/Angular dropdowns)

For custom dropdowns, you typically need to click the dropdown to expand it, then click the desired option.


1. Handling HTML <select> Dropdown

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




Java Code (Playwright):


import com.microsoft.playwright.*;


public class DropdownSelectExample {
  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();

      // Go to a page with a select dropdown
      page.navigate("https://rahulshettyacademy.com/AutomationPractice/");

      
      // Select option by value
      page.locator("#dropdown-class-example").selectOption("option2");

      
      // To see the execution
      Thread.sleep(2000);


      System.out.println("Option selected.");
    }
  }
}


Step by Step above code explanation:

(a) Navigate to the url by page.navigate()
(b) find dropdown by page.locator() and click the dropdown menu
(c) Pause the execution for 2 seconds



2. Handling Custom Dropdown (Non-Select)

Java Code (Playwright):

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 to view if not visible
      page.locator("#menu1").scrollIntoViewIfNeeded();

      // Click to open the custom dropdown
      page.locator("#menu1").click();

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

      System.out.println("Custom option selected.");
    }
  }
}


Step by Step above code explanation:

(a) Navigate to the url by page.navigate()
(b) Scroll to the menu on the page if needed
(c) Click on menu bar
(d) Click on the menu options