使用 Selenium 的 Python WebDriver 选择 <option> 的正确方法是什么

软件测试 Python 网络驱动程序
2022-01-20 18:43:56

我想选择一个使用 Python WebDriver的<option>孩子。<select>

WebElement我有一个我希望选择的选项的参考,并尝试过select()click()方法,但都不起作用。

正确的选择方法是<option>什么?

4个回答

我认为使用selenium.webdriver.support.ui.Select是最干净的方式:

from selenium import webdriver
from selenium.webdriver.support.ui import Select

b = webdriver.Firefox()

# navigate to the page
select = Select(b.find_element_by_id(....))
print select.options
print [o.text for o in select.options] # these are string-s
select.select_by_visible_text(....)

使用这种方法也是最快的方法。我写成fast_multiselectmultiselect_set_selections. multiselect_set_selections在对每个约 20 个项目的列表进行4 次调用的测试中,平均运行时间为 16.992 秒,其中fast_multiselect只有 10.441 秒。后者也不那么复杂。

 from selenium.webdriver.support.ui import Select

 def fast_multiselect(driver, element_id, labels):
     select = Select(driver.find_element_by_id(element_id))
     for label in labels:
         select.select_by_visible_text(label)

我发现的最简单的方法是按照以下方式做一些事情:

el = driver.find_element_by_id('id_of_select')
for option in el.find_elements_by_tag_name('option'):
    if option.text == 'The Options I Am Looking For':
        option.click() # select() in earlier versions of webdriver
        break

如果有大量选项,这可能会出现一些运行时问题,但对我们来说就足够了。

此代码也适用于多选

def multiselect_set_selections(driver, element_id, labels):
    el = driver.find_element_by_id(element_id)
    for option in el.find_elements_by_tag_name('option'):
        if option.text in labels:
            option.click()

然后您可以转换以下字段

# ERROR: Caught exception [ERROR: Unsupported command [addSelection | id=deformField7 | label=ALL]]

进入这个电话

multiselect_set_selections(driver, 'deformField7', ['ALL'])

多选错误,如下所示:

 # ERROR: Caught exception [ERROR: Unsupported command [addSelection | id=deformField5 | label=Apr]]
 # ERROR: Caught exception [ERROR: Unsupported command [addSelection | id=deformField5 | label=Jun]]

将通过一个电话修复:

multiselect_set_selections(driver, 'deformField5', ['Apr', 'Jun'])

类似于 Will 的答案,但<select>通过其元素名称找到 ,并根据<option>文本单击。

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()

我遇到了类似的问题,并且能够通过 xpath 查找元素来解决它:

from selenium import webdriver
b = webdriver.Firefox()
#...some commands here
b.find_element_by_xpath("//select/option[@value='The Options I am Looking for']").click()