簡體   English   中英

如何使用Selenium - Python選擇下拉菜單選項值

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

我需要從下面的下拉菜單中選擇一個元素。

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

但它讓我有錯誤。 我怎樣才能做到這一點。

官方文檔

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

您可以迭代所有選項,如下所示:

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

嗨,請簡單地使用一行代碼即可

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

希望能幫助到你

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM