About this question
I need to interact with a drop-down menu on a webpage and select a specific option. Here's an example of the HTML structure of the drop-down menu:

How can I programmatically select an option, such as "Mango"?
I need to interact with a drop-down menu on a webpage and select a specific option. Here's an example of the HTML structure of the drop-down menu:

How can I programmatically select an option, such as "Mango"?
Log in to share your answer and help other learners.
Log in to answerBest Answer · By JanBask QA Expert
Answered on Dec 19, 2024
To select a value from the given drop-down menu using Selenium in Python, follow these steps:
Code Solution:
from selenium import webdriver
from selenium.webdriver.support.ui import Select
# Step 1: Set up the WebDriver and navigate to the webpage
driver = webdriver.Chrome() # Replace with your browser driver if not using Chrome
driver.get("URL_OF_THE_WEBPAGE") # Replace with the URL of your page
# Step 2: Locate the drop-down element by its ID
dropdown = driver.find_element("id", "fruits01")
# Step 3: Create a Select object and interact with the drop-down
select = Select(dropdown)
# Option 1: Select an option by visible text
select.select_by_visible_text("Mango")
# Option 2: Select an option by value
# select.select_by_value("2")
# Option 3: Select an option by index
# select.select_by_index(2) # Index starts at 0
# Step 4: Clean up
driver.quit()Explanation of the Code:
Locate the select element:
Use the find_element method with an appropriate locator (e.g., "id", "name", or "class name").
Create a Select object:
The Select class makes it easy to interact with drop-down menus in Selenium.
Select an option:
Use select_by_visible_text("Mango") to select by the displayed text.
Use select_by_value("2") to select by the value attribute.
Use select_by_index(2) to select by the index (starting from 0).
Close the browser:
Always quit the WebDriver after completing your tasks to release resources.
Example Output:
When the code executes, the "Mango" option will be selected in the drop-down menu.
Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.
Step-by-step QA Testing guides from industry experts
Common QA Testing interview questions, answered
Guides, tips and career advice on QA Testing from JanBask experts.
Selenium Selenium Tutorial: Complete Guide to Automation Testing for Beginners
The Selenium tutorial covers both fundamental & advanced Selenium concepts. It is for individuals at all levels. Learn about…
QA Testing Software Testing Basics: Fundamentals, Principles, Lifecycle & Best Practices
Learn software testing basics, including key principles, lifecycle stages, types of testing, and best practices. A complete…
QA Testing You Can’t Miss the Top 20 Security Testing Interview Questions
Are you getting ready for your information security interview? Get a hold of the top 20 information security interview questions…