使用 Playwright for 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())

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


慕妹3146593
浏览 160回答 5
5回答

四季花海

在尝试了许多不同的变体之后,我猜出了一个有效的语法handle.selectOption({"label":&nbsp;"Banana"})

慕斯王

Playwright for Python 的一个工作示例:page.select_option('select#colors', label='Banana')或者对于 JavaScript:await page.selectOption('select#colors', { label: 'Banana' });

开满天机

您还可以使用索引或值来选择选项:handle.selectOption([{'label': 'Banana'}])&nbsp; # selects 'Banana'handle.selectOption([{'index': 3}])&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# selects 'Carrot'handle.selectOption([{'value': ''}])&nbsp; &nbsp; &nbsp; &nbsp; # selects the empty option (works even though it is disabled)

猛跑小猪

不需要句柄,直接使用页面或者框架即可。使用剧作家-python:page.select_option('select#name-fruit',&nbsp;label='Banana') page.select_option('select#name-fruit',&nbsp;value='')

慕的地8271018

如果您必须根据“包含”选择列表选项,这就是我使用的基本上得到一个定位器来查找带有文本的选项获取选项的全文使用该全文来选择选项&nbsp; dropdown_locator = page.locator(DROPDOWN_LOCATOR)&nbsp; dropdown_locator = dropdown_locator.filter(has_text="Banana")&nbsp; options_txt = activity_locator.text_content()&nbsp; options = options_txt.split('\n')&nbsp; print("Monkey searching banana in " + str(options))&nbsp; full_label = ""&nbsp; for item in options:&nbsp; &nbsp; &nbsp; if "Banana" in item:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; full_label = item.strip()&nbsp; print(full_label)&nbsp; if len(full_label) != 0:&nbsp; &nbsp; &nbsp; page.select_option(DROPDOWN_LOCATOR, label=full_label)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python