简体   繁体   English

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

[英]How to select a drop-down menu option value using Selenium - Python

I need to select an element from the below drop-down menu. 我需要从下面的下拉菜单中选择一个元素。

<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>

I have tried using this code, 我试过使用这段代码,

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

but it returned me with errors. 但它让我有错误。 How can I accomplish the same. 我怎样才能做到这一点。

From the 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

you can iterate trough all options like this: 您可以迭代所有选项,如下所示:

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()

Hi please simply use one line code it will work 嗨,请简单地使用一行代码即可

// 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");

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM