Python - Selenium - Select single and multiple options

By xngo on June 18, 2019

The Python code below shows you how to select single and multiple options using Selenium.

import time
 
from selenium import webdriver
from selenium.webdriver.support.ui import Select
 
# Create chrome driver.
driver = webdriver.Chrome()
 
# Open the webpage.
driver.get("https://openwritings.net/sites/default/files/selenium-test-pages/select.html")
 
# Pause for 5 seconds for you to see the initial state.
time.sleep(5)
 
 
# Single Selection: Select July.
##########################################################################################
select = Select(driver.find_element_by_id("single-selection"))
select.select_by_visible_text("July")
 
 
# Multiple Selections: Use variations of locators to select February, August and November.
##########################################################################################
# Find <select> element of "Multiple selection" using XPATH locator.
select = Select(driver.find_element_by_xpath("//select[@multiple='multiple' and @size=12]"))
 
# Clear all selected entries.
select.deselect_all();
 
# Select February, August and November using different functions.
select.select_by_index(1);                 # February
select.select_by_value("Aug");             # Select <option ... value="Aug">...</option>
select.select_by_visible_text("November"); # Select <option ...>November</option>
 
 
# Pause for 10 seconds so that you can see the results.
time.sleep(10)
 
# Close.
driver.close()

Here is a video showing the code above in action.

Video showing selenium select options

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.