DROPDOWNS & MULTI-SELECT LISTS

Master dropdown selection mechanisms in Playwright with Python: native HTML <select> elements, select_option strategies (value, label, index), multi-select lists, custom ARIA comboboxes, and searchable filter dropdowns.

📋 Dropdown & Select List Architecture in Playwright

Handling select inputs in web automation falls into two distinct paradigms: native HTML <select> elements and custom ARIA-compliant comboboxes built with modern front-end frameworks (React, Angular, Vue). For native elements, Playwright provides the built-in locator.select_option() method, which performs actionability checks, auto-waits for option elements to attach, and selects by value attribute, visible label, or zero-based index while triggering native input and change events. For custom UI dropdowns, Playwright leverages accessibility roles (combobox, listbox, and option) to ensure consistent user interactions.

1. select_option() Selection Strategies Overview
Playwright's select_option() accepts multiple argument types, allowing test engineers to target options flexibly depending on how the back-end encodes option items.
Selection Criteria Patterns
WAYS TO TARGET NATIVE <option> ELEMENTS:

1. By Value Attribute (Direct String):
   page.locator("#country-select").select_option("IN")
   page.locator("#country-select").select_option(value="IN")

2. By Visible Label Text (Human-Readable):
   page.locator("#country-select").select_option(label="India")

3. By Zero-Based Index:
   page.locator("#country-select").select_option(index=2)

4. By Element Handle Locator:
   option_loc = page.locator("option#special-opt")
   page.locator("#country-select").select_option(element=option_loc)

5. Multiple Selections for <select multiple>:
   page.locator("#skills-select").select_option(["python", "playwright", "docker"])
Engine Rule: select_option() returns a list of values that were successfully selected on the target <select> element.
Real-Time Example 1: Selecting by Visible Text (Label)
Selecting by visible label is the most user-centric approach because it mirrors what real users see on screen, insulating test scripts from internal back-end ID changes.
Python (select_option by Label)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
""") select_dropdown = page.get_by_label("Billing Currency") # Select option matching visible text exactly selected_values = select_dropdown.select_option(label="Euro (EUR)") # Web-first assertion on input value expect(select_dropdown).to_have_value("eur") print(f"Option selected successfully! Returned value list: {selected_values}") print(f"Verified current dropdown value: '{select_dropdown.input_value()}'") browser.close()
Output: Option selected successfully! Returned value list: ['eur'] Verified current dropdown value: 'eur'
Real-Time Example 2: Selecting by Value Attribute & Index
When visible text is localized into multiple regional languages or dynamically translated, targeting the immutable value attribute or numeric index ensures deterministic execution.
Python (Selection by Value & Index)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
""") priority_select = page.get_by_label("Ticket Priority") # 1. Select by explicit value attribute priority_select.select_option(value="critical") expect(priority_select).to_have_value("critical") print(f"Selected by value: '{priority_select.input_value()}'") # 2. Select by zero-based index (index=1 corresponds to P2 - Medium) priority_select.select_option(index=1) expect(priority_select).to_have_value("medium") print(f"Selected by index (1): '{priority_select.input_value()}'") browser.close()
Output: Selected by value: 'critical' Selected by index (1): 'medium'
Real-Time Example 3: Multi-Select Lists (<select multiple>)
For multi-select dropdowns containing the multiple attribute, pass a list of values, labels, or dictionary criteria to select several options in a single call.
Python (Multi-Select Automation)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
""") multi_select = page.get_by_label("Assigned Automation Frameworks") # Select multiple options simultaneously by passing an array selected = multi_select.select_option(["playwright", "pytest", "docker"]) print(f"Values selected simultaneously: {selected}") # Verify selected options via JavaScript DOM evaluation selected_values = multi_select.evaluate("""select => Array.from(select.selectedOptions).map(opt => opt.value) """) expect(multi_select).to_have_values(["playwright", "pytest", "docker"]) print(f"Verified selected values in DOM: {selected_values}") # Deselect all options by passing an empty list multi_select.select_option([]) cleared_values = multi_select.evaluate("select => select.selectedOptions.length") print(f"Total options selected after clear: {cleared_values}") browser.close()
Output: Values selected simultaneously: ['playwright', 'pytest', 'docker'] Verified selected values in DOM: ['playwright', 'pytest', 'docker'] Total options selected after clear: 0
Real-Time Example 4: Custom ARIA Comboboxes & Dropdown Menus
Modern UI component libraries (Material UI, Ant Design, React Select) render custom dropdowns using div or button wrappers with ARIA roles combobox and listbox.
Python (ARIA Combobox Automation)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    # Custom simulated accessible combobox widget
    page.set_content("""
        
""") # 1. Click to expand custom combobox trigger combobox = page.get_by_role("combobox", name="Select Deployment Cloud Region") expect(combobox).to_have_attribute("aria-expanded", "false") combobox.click() # 2. Select option from expanded listbox using role="option" target_option = page.get_by_role("option", name="Asia Pacific (Mumbai)") expect(target_option).to_be_visible() target_option.click() # 3. Verify combobox displays updated selection expect(combobox).to_have_text("Asia Pacific (Mumbai)") expect(combobox).to_have_attribute("aria-expanded", "false") print(f"Custom combobox state verified: '{combobox.inner_text()}'") browser.close()
Output: Custom combobox state verified: 'Asia Pacific (Mumbai)'
Real-Time Example 5: Searchable Autocomplete Filter Dropdowns
Searchable dropdowns (like Select2 or React-Select) require typing a search token into an input, waiting for filtered options to display, and pressing Enter or clicking the target match.
Python (Searchable Autocomplete Selection)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
""") country_input = page.get_by_label("Country Destination") # Type query to trigger dropdown filter country_input.fill("Ind") # Target specific filtered item from the results list target_match = page.locator("#results-menu .item").filter(has_text="India") expect(target_match).to_be_visible() target_match.click() # Verify input retains chosen selection expect(country_input).to_have_value("India") print(f"Searchable filter selected: '{country_input.input_value()}'") browser.close()
Output: Searchable filter selected: 'India'
Real-Time Example 6: Grouped Dropdowns (<optgroup>)
Automating nested options partitioned into categorized groups (<optgroup label="...">). Playwright handles grouped options without needing to interact with the parent group header.
Python (Grouped <optgroup> Selection)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
""") car_select = page.get_by_label("Automotive Category") # Select option situated inside the second optgroup car_select.select_option(label="Tata Nexon EV") expect(car_select).to_have_value("tata-ev") print(f"Selected EV Model: '{car_select.input_value()}'") car_select.select_option(value="hyundai-creta") expect(car_select).to_have_value("hyundai-creta") print(f"Selected ICE Model: '{car_select.input_value()}'") browser.close()
Output: Selected EV Model: 'tata-ev' Selected ICE Model: 'hyundai-creta'
Real-Time Example 7: Extracting All Available Options from a Dropdown
Inspect dropdown metadata by extracting all child <option> elements into Python data structures to verify expected choices, sorting order, or option counts.
Python (Option Scraping & Verification)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
    """)

    role_dropdown = page.locator("#role-select")
    options = role_dropdown.locator("option")

    # Verify total options available
    expect(options).to_have_count(3)

    # Extract visible label texts for all options
    option_labels = options.all_inner_texts()
    print("Discovered Dropdown Options:")
    for idx, text in enumerate(option_labels, 1):
        print(f"  [{idx}] {text}")

    # Extract all value attributes using JavaScript evaluate
    option_values = role_dropdown.evaluate("""select => 
        Array.from(select.options).map(opt => opt.value)
    """)
    print(f"Extracted Value List: {option_values}")

    browser.close()
Output: Discovered Dropdown Options: [1] Viewer Only [2] Content Editor [3] System Administrator Extracted Value List: ['viewer', 'editor', 'admin']
Real-Time Example 8: Handling Dynamic Dependent Cascading Dropdowns
Cascading dropdowns populate child options based on the parent selection (e.g., State updates District choices via an asynchronous AJAX response). Auto-waiting ensures child elements are ready.
Python (Cascading Dropdown Synchronization)
from playwright.sync_api import sync_playwright, expect

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)
    page = browser.new_page()

    page.set_content("""
        
""") state_select = page.get_by_label("State") city_select = page.get_by_label("City") # Initially child city dropdown is disabled expect(city_select).to_be_disabled() # Select Maharashtra in parent dropdown state_select.select_option(value="MH") # Auto-waiting assertion: City select becomes enabled dynamically expect(city_select).to_be_enabled() # Select Pune in child dropdown city_select.select_option(label="Pune") expect(city_select).to_have_value("pune") print(f"Cascading flow completed: State={state_select.input_value()} -> City={city_select.input_value()}") browser.close()
Output: Cascading flow completed: State=MH -> City=pune
Real-Time Example 9: Dropdowns Complete Reference Matrix
A comprehensive reference summary of all core selection methods, parameters, and assertions for dropdowns in Playwright Python.
Dropdown Methods Reference Matrix
PLAYWRIGHT DROPDOWNS & SELECT OPTIONS MATRIX:
┌──────────────────────────────┬──────────────────────────────┬─────────────────────────────────────────────────────────┐
│ Method / Operation           │ Parameters / Criteria        │ Description / Primary Use Case                          │
├──────────────────────────────┼──────────────────────────────┼─────────────────────────────────────────────────────────┤
│ select_option(value="...")   │ value: str / List[str]       │ Targets <option value="..."> attribute directly.        │
│ select_option(label="...")   │ label: str / List[str]       │ Targets visible text rendered inside <option> tags.     │
│ select_option(index=N)       │ index: int / List[int]       │ Targets option by zero-based position in the list.      │
│ select_option([...])         │ List of values or criteria   │ Selects multiple choices on <select multiple>.          │
│ select_option([])            │ Empty List                   │ Clears all active selections in a multi-select list.    │
│ locator.input_value()        │ None (returns str)           │ Returns current selected value attribute of <select>.   │
│ expect(loc).to_have_value()  │ str / Pattern                │ Web-first assertion verifying current selected value.   │
│ expect(loc).to_have_values() │ List[str / Pattern]          │ Web-first assertion for multi-select value lists.       │
│ get_by_role("combobox")      │ name: str                    │ Locates native select or ARIA combobox trigger.         │
│ get_by_role("option")        │ name: str                    │ Locates individual selectable item in custom listboxes. │
└──────────────────────────────┴──────────────────────────────┴─────────────────────────────────────────────────────────┘
Engineering Best Practice: Use select_option(label=...) for native HTML <select> elements to maintain readable tests; for custom UI component libraries, automate via accessible combobox and option roles.