Using Playwright for Python, how do I select an option from a drop down list?

Viewed 8626

This is a followup to this question on the basic functionality of Playwright for Python.

How do I select an option from a drop down list?

This example remote controls a vuejs-webseite that has a drop down list of fruits like "Apple", "Banana", "Carrot", "Orange"

Here I want to select the option "Banana"

from playwright import sync_playwright
import time

URL = '<my url>'

with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.newPage()
    page.goto(URL)

    # identify this element by ID. Wait for it first
    new_selector = 'id=name-fruit'
    page.waitForSelector(new_selector)
    handle = page.querySelector(new_selector)

    # at this point I have the element and can print the content
    print(handle.innerHTML())

The drop down list HTML like this

<select data-v-c2cef47a="" id="name-fruit" autocomplete="true" class="form-select__select">
    <option data-v-c2cef47a="" disabled="disabled" value=""><!----></option>
    <option data-v-c2cef47a="" value="[object Object]"> Apple </option>
    <option data-v-c2cef47a="" value="[object Object]"> Banana </option>
    <option data-v-c2cef47a="" value="[object Object]"> Carrot </option>
    <option data-v-c2cef47a="" value="[object Object]"> Orange </option> 
</select>

in Selenium, I would select an option like this

from selenium.webdriver.support.ui import Select
Select(handle).select_by_visible_text('Banana')  # Note: no spaces needed!

The Javascript docs for Playwright have this, which is not exactly the same, because it seems to identify the object at the same time.

// Single selection matching the label
await page.selectOption('select#colors', { label: 'Blue' });

How do I do the selection in Playwright for Python?

I tried both of these and nothing happens.

handle.selectOption("text=Banana") 
handle.selectOption("text= Banana ")
4 Answers

After trying many different variants, I guessed a working syntax

handle.selectOption({"label": "Banana"})

A working example for Playwright for Python:

page.select_option('select#colors', label='Banana')

or for JavaScript:

await page.selectOption('select#colors', { label: 'Banana' });

See here for further handling of how to interact with selectors and how to use it in different languages and scenarios like JavaScript.

You can also alternatively use the index or the value to select an option:

handle.selectOption([{'label': 'Banana'}])  # selects 'Banana'
handle.selectOption([{'index': 3}])         # selects 'Carrot'
handle.selectOption([{'value': ''}])        # selects the empty option (works even though it is disabled)

You don't need the handle, you can use the page or frame directly.

Using playwright-python:

page.select_option('select#name-fruit', label='Banana')
page.select_option('select#name-fruit', value='')
Related