这是此 question 的后续关于 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 中进行选择?我尝试了这两种方法,但没有任何 react 。
handle.selectOption("text=Banana")
handle.selectOption("text= Banana ")
最佳答案
在尝试了许多不同的变体之后,
我猜到了一个有效的语法
handle.selectOption({"label": "Banana"})
关于python - 使用 Playwright for Python,如何从下拉列表中选择一个选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64306147/