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.

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

7 Comments

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'
Sorry for python please use send_keys ,i am form java so it was a typo error also i have updated sendkeys for python
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); ??
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);
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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.