如何使用Python选择Selenium下拉菜单值?

2024-04-24 20:56:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要从下拉菜单中选择一个元素。

例如:

<select id="fruits01" class="select" name="fruits">
  <option value="0">Choose your fruits:</option>
  <option value="1">Banana</option>
  <option value="2">Mango</option>
</select>

1)首先我必须单击它。我这样做:

inputElementFruits = driver.find_element_by_xpath("//select[id='fruits']").click()

2)之后,我必须选择好的元素,比如Mango

我试着用inputElementFruits.send_keys(...)来做,但没有成功。


Tags: nameid元素yourvalueselectclassbanana
3条回答

首先需要导入Select类,然后创建Select类的实例。 创建Select类的实例后,可以对该实例执行Select方法,从下拉列表中选择选项。 这是密码

from selenium.webdriver.support.select import Select

select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)

除非您的click正在触发某种ajax调用来填充列表,否则实际上不需要执行click。

只需找到元素,然后枚举选项,选择所需的选项。

下面是一个例子:

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

您可以在中阅读更多内容:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver

Selenium提供了使用select -> option构造的方便^{} class

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

driver = webdriver.Firefox()
driver.get('url')

select = Select(driver.find_element_by_id('fruits01'))

# select by visible text
select.select_by_visible_text('Banana')

# select by value 
select.select_by_value('1')

另见:

相关问题 更多 >