5

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

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

这个示例远程控制一个 vuejs-webseite,它有一个下拉列表的水果,如“Apple”、“Banana”、“Carrot”、“Orange”

在这里我要选择“香蕉”选项

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())

下拉列表 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>

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

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

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

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

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

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

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

4 回答 4

5

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

handle.selectOption({"label": "Banana"})
于 2020-10-11T17:04:00.027 回答
2

Playwright for Python 的一个工作示例:

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

或者对于 JavaScript:

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

有关如何与选择器交互以及如何在不同的语言和场景(如 JavaScript)中使用它的进一步处理,请参见此处。

于 2021-06-23T07:49:39.957 回答
1

您也可以使用索引或值来选择一个选项:

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)
于 2020-12-22T00:22:25.840 回答
1

不需要句柄,直接使用页面或框架即可。

使用 playwright-python:

page.select_option('select#name-fruit', label='Banana')
page.select_option('select#name-fruit', value='')
于 2021-05-06T08:57:42.627 回答