Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 761
404 Avatar asked Dec 06 '22 18:12

404


1 Answers

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
like image 199
boechat107 Avatar answered Jan 02 '23 22:01

boechat107