使用 Playwright for Python,如何从下拉列表中选择选项?

576*_*76i 8 python playwright playwright-python

这是关于 Playwright for Python 基本功能的问题的后续内容。

如何从下拉列表中选择一个选项

此示例远程控制一个 vuejs 网站,该网站具有“苹果”、“香蕉”、“胡萝卜”、“橙子”等水果的下拉列表

这里我想选择选项“香蕉”

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())
Run Code Online (Sandbox Code Playgroud)

下拉列表 HTML 像这样

<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>
Run Code Online (Sandbox Code Playgroud)

在 Selenium 中,我会选择这样的选项

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

Playwright 的 Javascript 文档有这个,这并不完全相同,因为它似乎同时识别了对象。

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

如何在 Playwright for Python 中进行选择?

我尝试了这两种方法,但没有任何反应。

handle.selectOption("text=Banana") 
handle.selectOption("text= Banana ")
Run Code Online (Sandbox Code Playgroud)

576*_*76i 6

在尝试了许多不同的变体之后,我猜出了一个有效的语法

handle.selectOption({"label": "Banana"})
Run Code Online (Sandbox Code Playgroud)

  • 对于未来的访问者,语法现在为“ElementHandle.select_option(label="Banana")”。 (2认同)