How to select a drop-down menu value with Selenium using Python?
Selenium provides a convenient Select
class to work with select -> option
constructs:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
driver = webdriver.Firefox()
driver.get('url')
select = Select(driver.find_element_by_id('fruits01'))
# select by visible text
select.select_by_visible_text('Banana')
# select by value
select.select_by_value('1')
See also:
- What is the correct way to select an using Selenium's Python WebDriver?
I hope this code will help you.
from selenium.webdriver.support.ui import Select
dropdown element with id
ddelement= Select(driver.find_element_by_id('id_of_element'))
dropdown element with xpath
ddelement= Select(driver.find_element_by_xpath('xpath_of_element'))
dropdown element with css selector
ddelement= Select(driver.find_element_by_css_selector('css_selector_of_element'))
Selecting 'Banana' from a dropdown
- Using the index of dropdown
ddelement.select_by_index(1)
- Using the value of dropdown
ddelement.select_by_value('1')
- You can use match the text which is displayed in the drop down.
ddelement.select_by_visible_text('Banana')
Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.
Just find the element and then enumerate the options, selecting the option(s) you want.
Here is an example:
from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()
You can read more in:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver
firstly you need to import the Select class and then you need to create the instance of Select class. After creating the instance of Select class, you can perform select methods on that instance to select the options from dropdown list. Here is the code
from selenium.webdriver.support.select import Select
select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)