Introduction
Selecting options from dropdown menus helps automate choices on web pages easily.
from selenium.webdriver.support.ui import Select select = Select(web_element) # Select by value select.select_by_value('value') # Select by visible text select.select_by_visible_text('text') # Select by index select.select_by_index(index)
web_element must be a <select> HTML element.value attribute is 'option1'.select.select_by_value('option1')select.select_by_visible_text('Option Two')select.select_by_index(2)from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select import time # Setup driver (using Chrome here) driver = webdriver.Chrome() # Open a simple page with a dropdown html = ''' <html> <body> <select id='fruits'> <option value='apple'>Apple</option> <option value='banana'>Banana</option> <option value='cherry'>Cherry</option> </select> </body> </html> ''' # Load the HTML content driver.get('data:text/html;charset=utf-8,' + html) # Find the select element select_element = driver.find_element(By.ID, 'fruits') # Create Select object select = Select(select_element) # Select by value select.select_by_value('banana') print('Selected by value:', select.first_selected_option.text) # Select by visible text select.select_by_visible_text('Cherry') print('Selected by text:', select.first_selected_option.text) # Select by index select.select_by_index(0) print('Selected by index:', select.first_selected_option.text) # Close driver driver.quit()
first_selected_option to check which option is currently selected.select_by_value to pick an option by its value attribute.select_by_visible_text to pick an option by what the user sees.select_by_index to pick an option by its position number.select_by_visible_text selects dropdown options by the text users see.select_by_value uses the option's value attribute, select_by_index uses position, and select_option_by_text is not a valid method.select_by_value.select.select_by_value('option1') is correct.from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('dropdown'))
select.select_by_index(2)select = Select(driver.find_element_by_id('dropdown'))
select.select_by_value(3)<option value='a'>Apple</option> <option value='b'>Banana</option> <option value='c'>Apple</option> <option value='d'>Date</option>
select_by_visible_text('Apple') selects the first 'Apple' option only.select_by_value('c') selects it reliably.Pass the test and this pattern moves unknown