4

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.

404
  • 1,115
  • 2
  • 11
  • 21

3 Answers3

10

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
Deepak Garud
  • 977
  • 10
  • 18
boechat107
  • 1,654
  • 14
  • 24
3

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()
MMMM
  • 3,320
  • 8
  • 43
  • 80
2

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

Rajnish Kumar
  • 2,828
  • 5
  • 25
  • 39
  • For this answer i am getting the following error driver.find_element_by_id("fruitType").sendKeys("jumbo fruit 4"); AttributeError: 'WebElement' object has no attribute 'sendKeys' – 404 Apr 07 '16 at 09:51
  • Sorry for python please use send_keys ,i am form java so it was a typo error also i have updated sendkeys for python – Rajnish Kumar Apr 07 '16 at 09:54
  • so is it like select = Select(driver.find_element_by_xpath("//select[@id='fruitType' and @class='chosen']")) driver.find_element_by_id("fruitType").send_keys("jumbo fruit 4); ?? – 404 Apr 07 '16 at 10:03
  • no no select statement not this line select = Select(driver.find_element_by_xpath("//select[@id='fruitType' and @class='chosen']")) .only this line driver.find_element_by_id("fruitType").send_keys("jumbo fruit 4); – Rajnish Kumar Apr 07 '16 at 10:05
  • Please use a universal wait for driver as error shows ElementNotVisibleException: Message: Element is not currently visible and so may not be interacted with. apply something like wait of some seconds before option selection – Rajnish Kumar Apr 07 '16 at 10:21
  • will time.sleep(5) do ? – 404 Apr 07 '16 at 10:32
  • driver.implicitly_wait(10) # seconds or time.sleep(NUM) – Rajnish Kumar Apr 07 '16 at 10:34