2016-04-07 131 views
2

我需要從下面的下拉菜單中選擇一個元素。如何使用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() 

但它返回我的錯誤。 我該怎麼做才能做到這一點。

回答

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

希望它可以幫助

+0

對於這個答案,我收到以下錯誤 driver.find_element_by_id(「fruitType」)。sendKeys(「jumbo fruit 4」); AttributeError:'WebElement'對象沒有屬性'sendKeys' – 404

+0

對不起,請使用send_keys,我是表單java,所以這是一個錯字錯誤,我也更新了python的sendkeys –

+0

所以它就像select = Select(driver.find_element_by_xpath (「// select [@ id ='fruitType'and @ class ='selected']」)) driver.find_element_by_id(「fruitType」)。send_keys(「jumbo fruit 4」); – 404

2

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 
0

你可以循環槽這樣所有選項:

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() 
相關問題