How to Select an Option from a Dropdown Using Python WebDriver

How to Select an Option from a Dropdown Using Python WebDriver

3 July 2024 Stephan Petzl Leave a comment QA

When working with Selenium WebDriver in Python, selecting an option from a dropdown menu can sometimes be challenging. Here, we provide a comprehensive guide to help you achieve this effectively.

Method 1: Using select_by_visible_text from selenium.webdriver.support.ui.Select

The most recommended and cleanest approach is to use the Select class from selenium.webdriver.support.ui. This method is straightforward and efficient for both single and multi-select dropdowns.

from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Firefox()
driver.get("your-url-here")

select = Select(driver.find_element_by_id('your-select-element-id'))
select.select_by_visible_text('Option Text')

This approach is not only simple but also faster compared to iterating through each option manually. It is particularly useful for handling multiple options efficiently.

Method 2: Iterating Through Options

Another common method is to manually iterate through each option in the dropdown. While this method is more verbose, it can be useful in specific scenarios, such as when dealing with dynamic dropdowns.

el = driver.find_element_by_id('your-select-element-id')
for option in el.find_elements_by_tag_name('option'):
    if option.text == 'Option Text':
        option.click()
        break

This method allows for more custom logic, such as handling multi-select dropdowns:

def multiselect_set_selections(driver, element_id, labels):
    el = driver.find_element_by_id(element_id)
    for option in el.find_elements_by_tag_name('option'):
        if option.text in labels:
            option.click()

Method 3: Using XPath

For those who prefer using XPath to locate elements, the following method is also effective:

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("your-url-here")

driver.find_element_by_xpath("//select[@name='your-select-element-name']/option[text()='Option Text']").click()

Conclusion

Selecting an option from a dropdown using Python WebDriver can be achieved through various methods. The Select class from selenium.webdriver.support.ui provides a clean and efficient way to handle dropdowns, while manual iteration and XPath methods offer additional flexibility for more complex scenarios.

For those working on mobile app testing, tools like Repeato can simplify the process even further. Repeato is a no-code test automation tool for iOS and Android that allows you to create, run, and maintain automated tests effortlessly. Its computer vision and AI capabilities make it particularly fast and user-friendly, ideal for quality assurance.

For more information, visit our Getting Started page or check out our blog for related articles.

Like this article? there’s more where that came from!