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

How to Handle IFrames in Playwright

 

What is an iframe?

An iframe (short for inline frame) is an HTML element that allows you to embed another HTML document inside the current webpage. It acts like a "window" or "frame" within the page, displaying content from the same site or even a completely different domain.


Purpose of iframes

  • Embedding external content such as videos, ads, maps, or third-party widgets (e.g., YouTube videos, Google Maps).
  • Sandboxing content for security, by isolating it from the main page’s scripts and styles.
  • Displaying independent documents without navigating away from the parent page.

Characteristics of iframes
  • Independent browsing context – An iframe has its own DOM (Document Object Model), meaning scripts and styles inside it do not directly interfere with the parent page.
  • Isolation – Because of browser security rules (like the Same-Origin Policy), interaction between the parent page and iframe is restricted if the iframe loads content from a different domain.
  • Resizable area – By default, an iframe is a rectangular region that can be given specific width and height.
  • Nested structure – An iframe can contain another iframe inside it, leading to multiple layers of embedded documents.

Advantages of iframes
  • Allows embedding of rich, external content without duplicating code.
  • Useful for modular design, separating different parts of a website.
  • Provides a security boundary when used with sandboxing attributes.

Disadvantages of iframes
  • Can negatively impact performance, as each iframe loads a separate webpage.
  • SEO (Search Engine Optimization) issues, since search engines may not index iframe content properly.
  • User experience problems, especially if the iframe content is not responsive or doesn’t adapt well to different screen sizes.
  • Security risks if external content is embedded without restrictions.


Handling iframe in Playwright with Java involves accessing the frame object using Playwright's Frame class. Since elements inside an iframe are isolated from the main document, you need to switch to the Frame context first before interacting with any elements within it.
















Steps to Handle iframe in Playwright (Java):

  • Launch browser and navigate to the page
  • Locate the iframe using a selector
  • Get the Frame object from the iframe element
  • Use frame.locator(...) to interact with elements inside the iframe

Example Use Case:

Let’s say there's an iframe with a form input (example: on https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_input_text).









Java Code using Playwright:

import com.microsoft.playwright.*;

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

            // Navigate to a page containing an iframe
            page.navigate("https://demo.automationtesting.in/Frames.html");

            // Wait for the iframe to load
            FrameLocator frameLocator = page.frameLocator("#singleframe");

            // Locate input inside iframe and type text
            frameLocator.locator("input[type='text']").fill("Playwright Java");

            // Optional: Wait or assert
            page.waitForTimeout(3000);
        }
    }
}


Explanation:








  • page.frameLocator("#singleframe") – Selects the iframe by its ID.

  • frameLocator.locator("input[type='text']") – Accesses the input element inside the iframe.

  • .fill("Playwright Java") – Fills text in the input box.


Suggested Posts:

1. File Upload in Playwright
2. File Download in Playwright
3. Playwright with JUnit
4. Handle Dynamic Webtable in Playwright
5. Page Object Model in Playwright

Find Web Elements by XPath in Playwright

 

In Playwright, XPath is one of the strategies used to locate web elements within a page. XPath (XML Path Language) is a query language designed for navigating through elements and attributes in an XML or HTML document. Since web pages are structured as HTML documents (which are tree-like in nature), XPath expressions can be used to traverse and identify specific elements.

Why XPath is Useful in Playwright

  • Precise Location: XPath can identify elements that do not have unique IDs, names, or other easy selectors.
  • Complex Relationships: It allows finding elements based on their relationship to other elements, such as parent, child, sibling, or ancestor.
  • Attribute-Based Selection: You can locate elements based on attributes, text content, or a combination of conditions.
  • Dynamic Content: Useful in scenarios where element attributes like id or class keep changing but relative positions remain consistent.


Types of XPath in Playwright

1. Absolute XPath: Starts from the root (/html/...) and provides the full path. It is very fragile because even a small change in the structure breaks it.
2. Relative XPath: Starts from a specific node (//div[@class='example']) and is more reliable and flexible.


How Playwright Uses XPath
  • Playwright internally supports multiple selector engines, and XPath is one of them.
  • When you specify an XPath, Playwright traverses the DOM tree to locate the element that matches the given expression.
  • Once found, the element can be interacted with (clicked, typed into, verified, etc.).

Advantages of Using XPath
  • Works even when there are no unique IDs or CSS selectors.
  • Can combine multiple conditions (like text + attribute).
  • Handles nested and hierarchical structures well.

Disadvantages
  • More complex and harder to read than CSS selectors.
  • Slower compared to CSS because it often scans the whole DOM.
  • Fragile if the DOM structure changes frequently.


In Playwright Java, you can find elements using XPath by using the locator() method with the XPath expression prefixed by "xpath=".












Example: Find an element by XPath in Playwright Java.

Let’s take https://example.com as the sample website and find the <h1> element using XPath.


import com.microsoft.playwright.*;

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

      // Navigate to example website
      page.navigate("https://example.com");

      // Find element using XPath
      Locator heading = page.locator("xpath=//h1");

      // Print the heading text
      System.out.println("Heading: " + heading.textContent());
    }
  }
}


XPath Syntax Recap

  • //tagname: Selects all elements with the tag name.

  • //*[@attribute='value']: Selects elements by attribute.

  • //div[contains(text(),'Sample')]: Selects elements that contain specific text.


















Another Example with Attribute XPath

Locator element = page.locator("xpath=//*[@id='username']");

This selects an element with the id="username".



Suggested Posts:

1. File Upload in Playwright
2. File Download in Playwright
3. Playwright with JUnit
4. Handle IFrames in Playwright
5. Page Object Model in Playwright