0
0
Selenium Pythontesting~5 mins

Select by value, text, index in Selenium Python

Choose your learning style9 modes available
Introduction
Selecting options from dropdown menus helps automate choices on web pages easily.
When you want to pick a specific option from a dropdown by its value.
When you want to select an option by the visible text shown to users.
When you want to choose an option based on its position in the list.
Syntax
Selenium Python
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)
The web_element must be a <select> HTML element.
Index starts at 0 for the first option in the dropdown.
Examples
Selects the option whose value attribute is 'option1'.
Selenium Python
select.select_by_value('option1')
Selects the option that shows 'Option Two' to the user.
Selenium Python
select.select_by_visible_text('Option Two')
Selects the third option in the dropdown list (index 2).
Selenium Python
select.select_by_index(2)
Sample Program
This program opens a simple dropdown with three fruit options. It selects options by value, text, and index, printing the selected option each time.
Selenium Python
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()
OutputSuccess
Important Notes
Make sure the dropdown element is fully loaded before selecting options.
If the value, text, or index does not exist, Selenium will raise an error.
Use first_selected_option to check which option is currently selected.
Summary
Use select_by_value to pick an option by its value attribute.
Use select_by_visible_text to pick an option by what the user sees.
Use select_by_index to pick an option by its position number.