Selecting dropdown options in Selenium can be done using the Select class. Here's a checklist of how to select dropdown options in Selenium with Python, along with examples and expected output:
Select by Index:
Use the select_by_index() method to select an option by its index (0-based).
from selenium.webdriver.support.ui import Select
dropdown = Select(driver.find_element(By.ID, "dropdown_id"))
dropdown.select_by_index(1) # Selects the second option (index 1)
Select by Value:
Use the select_by_value() method to select an option by its "value" attribute.
dropdown.select_by_value("option_value") # Replace with the actual value
Select by Visible Text:
Use the select_by_visible_text() method to select an option by its visible text.
dropdown.select_by_visible_text("Option 2") # Replace with the actual text
Deselect All:
You can clear all selected options in a multi-select dropdown using the deselect_all() method.
dropdown.deselect_all()
Get Selected Options:
Use the all_selected_options property to get all selected options.
selected_options = dropdown.all_selected_options
for option in selected_options:
print("Selected option text:", option.text)
Get All Options:
Use the options property to get all available options in the dropdown.
all_options = dropdown.options
for option in all_options:
print("Option text:", option.text)
Check If an Option Is Selected:
Use the is_selected property to check if an option is selected.
option = dropdown.first_selected_option
if option.is_selected:
print("Option is selected")
else:
print("Option is not selected")
Expected output will vary depending on what you do with the selected options, but here are some expected outputs for the given examples:
The option at index 1 (the second option) will be selected.
An option with the specified value will be selected.
The option with the specified visible text will be selected.
All selected options will be displayed.
All available options will be displayed.
Whether the option is selected or not will be printed.
Top comments (0)