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

时间:2016-04-07 09:25:01

标签: python selenium selenium-webdriver selenium-firefoxdriver

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

<select class="chosen" id="fruitType" name="fruitType">
    <option value="">Select</option>
    <option value="1">jumbo fruit 1</option>
    <option value="2">jumbo fruit 2</option>
    <option value="3">jumbo fruit 3</option>
    <option value="4">jumbo fruit 4</option>
    <option value="5">jumbo fruit 5</option>
    <option value="8">jumbo fruit 6</option>
</select>

我尝试过使用此代码,

driver = webdriver.Firefox()
driver.find_element_by_xpath("//select[@name='fruitType']/option[text()='jumbo fruit 4']").click()

但它让我有错误。 我怎样才能做到这一点。

3 个答案:

答案 0 :(得分:4)

来自official documentation

from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_id('fruitType'))
# Now we have many different alternatives to select an option.
select.select_by_index(4)
select.select_by_visible_text("jumbo fruit 4")
select.select_by_value('4') #Pass value as string

答案 1 :(得分:1)

嗨,请简单地使用一行代码

// please note the if in case you have to select a value form a drop down with tag 
// name Select then use below code it will work like charm
driver.find_element_by_id("fruitType").send_keys("jumbo fruit 4");

希望有所帮助

答案 2 :(得分:1)

您可以通过以下所有选项进行迭代:

element = driver.find_element_by_xpath("//select[@name='fruitType']")
all_options = element.find_elements_by_tag_name("option")
for option in all_options:
    print("Value is: %s" % option.get_attribute("value"))
    option.click()