How to handle dropdown in Selenium Python?

Test Dropdown without Select Class in Selenium in real user conditions on real device cloud

Guide Banner Image
Home Guide How to handle dropdown in Selenium Python?

How to handle dropdown in Selenium Python?

The ‘dropdown’ is a navigation element of a website. It permits a selection of one or more than one option from a list. It’s an HTML element; you can use it in registration forms, search filter features, NavBar, etc.

But there are some drawbacks of dropdowns users might face also. Sometimes it creates a false impression so that the user might think that the dropdown is ‘filled’, but it actually remains ‘empty’. So, dropdown testing becomes a necessary part of automated UI testing.

Let us learn how to operate it with Selenium Python.

The Need for a Dropdown

  • The main advantage of using a dropdown is that it saves your apps/web pages from unnecessary space consumption by containing all the options within it.
  • It eliminates the problems like mistyping, misspelling, or wrong input from the users.
  • It helps find particular content on a web page without scrolling up and down.
  • Save users’ time on a large website. You can access your targeted content without wasting any time.
  • It sets the limit of options to choose from and helps users easily navigate.
  • Preserve screen space from unwanted content.
  • Also helps to navigate to another page.

What is Select Class in Selenium?

In Selenium with Python, the Select class can be used to interactwith <select> HTML elements, which are commonly known as dropdowns. This class is part of the selenium.webdriver.support.ui module and provides convenient methods to select and deselect options from dropdowns.

Why Use Select Class in Selenium Python To Handle Dropdowns?

The Select class handles dropdown menus (HTML <select> tags) easily and efficiently. Here’s why it’s preferred to handle dropdowns in Selenium Python:

1. Simplifies Dropdown Handling: Without Select, interacting with dropdowns would require manually locating and clicking individual <option> elements. Select compiles all that into easy-to-use methods.

2. Built Specifically for <select> Elements: It’s optimized to work only with standard HTML <select> dropdowns. This ensures consistent behavior, better handling of multi-select options, and support for getting all or selected options.

3. Cleaner & More Readable Code: Using the Select class results in cleaner, easier-to-maintain test scripts than manually iterating over options or simulating mouse clicks.

4. Supports Multiple Selection Scenarios: If a dropdown allows multiple selections (via multiple attribute), the Select class lets you:

  • Select/deselect multiple values
  • Use deselect_all() to reset selections

5. Provides Access to All Options: You can easily retrieve all dropdown options with select.options, useful for validation and dynamic checks.

How to handle dropdown in Selenium Python

Prerequisites

1. First, install Python. Use Command-

py –m pip install –U pip

2. Install Selenium in a Python environment. Run the command-

pip install selenium

3. Then import Selenium WebDriver and Keys classes.

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

After that, start your testing.

How to Select Option in Dropdown using Selenium Python

The Select class in Selenium is used to handle drop-down. Selenium WebDriver provides a class named ‘Select’. You need to import the Select class from it.

For using the methods of Select class we have to import in our code

'selenium.webdriver.support.select.Select'

By doing this you can also use the Select method. You can create an object of the select class by passing an element of the select tag within Select().

Later you can use this object in another method.

// Create an object of the Select class
Select select = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']")));

There are multiple methods to select dropdowns in Selenium Python. They are:

select_by_index(int index)

Index values are started from 0 and continue with an increment of +1. It means if there are five dropdown values then they will be 0,1,2,3, and 4. Suppose, you want to select the 3rd value from the dropdown then the index will be 2.

The dropdown syntax becomes-

select.select_by_index(2);

select _by_value(String value)

You have to pass a text as a parameter to select_by_value. Then it will match with the value attribute text so that the user can click the dropdown value for which it becomes matched. The syntax will be-

select.select_by_value(‘Selenium Python’);

select _by_visible_text(String text)

When you pass a text as a parameter to select_by_visible_text, it will match with the visible text attribute so that you can click the dropdown value for which it becomes matched.

The syntax will be-

select.select_by_visible_text(‘Selenium Python’);

Let us see an example of handling dropdown with the above three methods-

import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
from selenium.webdriver.support.select import Select

public class DropDown {

public static void main(String[] args) throws InterruptedException {

//Creating an instance of Chrome driver
WebDriver driver = new ChromeDriver();

//Step#2- Launching URL
driver.get("https://demoqa.com/select-menu");

//Maximizing window
driver.manage().window().maximize();

//Step#3- Selecting the dropdown element by locating its id
Select select = new Select(driver.findElement(By.id("oldSelectMenu")));

//Step#4- Printing the options of the dropdown
//Get list of web elements
List<WebElement> lst = select.getOptions();

//Looping through the options and printing dropdown options
System.out.println("The dropdown options are:");
for(WebElement options: lst)
System.out.println(options.getText());

//Step#5- Selecting the option as 'Purple'-- selectByIndex
System.out.println("Select the Option by Index 4");
select.selectByIndex(4);
System.out.println("Select value is: " + select.getFirstSelectedOption().getText());

//Step#6- Selecting the option as 'Magenta'-- selectByVisibleText
System.out.println("Select the Option by Text Magenta");
select.selectByVisibleText("Magenta");
System.out.println("Select value is: " + select.getFirstSelectedOption().getText());

//Step#7- Selecting an option by its value
System.out.println("Select the Option by value 6");
select.selectByValue("6");
System.out.println("Select value is: " + select.getFirstSelectedOption().getText());

driver.quit();
}
}
  • deselect_by_index(int index)

This method performs the opposite action of the select_by_index method. It means deselecting the selected index which matches the method argument. Here we selected the 2nd value from the dropdown. Thus the deselected index becomes 1. If there is no index selected for this action then Python Selenium throws ‘NoSuchElementException’.

select.deselect_by_index(1);
  • deselect _by_value(String value)

It deselects the value which matches the method argument.

select.deselect_by_value(‘Selenium Python’);
  • deselect _by_visible_text(String text)

It deselects the text which matches the method argument.

select.deselect_by_visible_text(‘Selenium Python’);

Test Multiple-Select dropdown

The Select class provides a ‘isMultiple()’ method. It has the features like:

  1. Select multiple values by calling the methods several times for multiple values.
  2. Validate whether the dropdown allows multiple values or not.
  3. Returns a Boolean value- true/false.
  4. By using multi-select elements you can implement other select methods.

Selenium Webdriver provides four types of methods to test whether your drop-down supports multi-select operation or not. They are-

  • options()
Returns all the options from the dropdown.

options(): List<WebElement>

// Get all the options of the dropdown
List<WebElement> Options = select.options();
  • first_selected_option()

Returns the first selected option from the dropdown.

first_selected_option(): WebElement
// Get the first selected option of the dropdown
WebElementFirstSelectedOption = select.getFirstSelectedOption();
  • all_selected_options()

Returns all the selected options.

all_selected_options():List<WebElement>
// Get all the selected option of the dropdown
List<WebElement>selectedOptions = select.getAllSelectedOptions();
  • deselect_all()

Clears all the selected options. If the selection doesn’t support multi-select then the Python Selenium will throw the ‘NotImplementedError’ exception.

deselect_all(): void
//Deselect all the options
select.deselect_all();

Note: The first three methods are valid for both single and multi-select. But the deselect_all() method is only valid for multi-select.

BrowserStack Automate Banner

Handling multi-select options in dropdown with Selenium Python

Here is a sample code to handle a multi-select element dropdown covering the above-mentioned methods:

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class MultiSelect {

public static void main(String[] args) throws InterruptedException {

//Creating an instance of Chrome driver
WebDriver driver = new ChromeDriver();

// Navigate to the URL
driver.get("https://demoqa.com/select-menu");

//Maximizing window
driver.manage().window().maximize();

//Selecting the multi-select element by locating its id
Select select = new Select(driver.findElement(By.id("cars")));

//Get the list of all the options
System.out.println("The dropdown options are -");

List<WebElement> options = select.getOptions();

for(WebElement option: options)
System.out.println(option.getText());

//Using isMultiple() method to verify if the element is multi-select, if yes go onto next steps else eit
if(select.isMultiple()){

//Selecting option as 'Opel'-- ByIndex
System.out.println("Select option Opel by Index");
select.selectByIndex(2);

//Selecting the option as 'Saab'-- ByValue
System.out.println("Select option saab by Value");
select.selectByValue("saab");

// Selecting the option by text
System.out.println("Select option Audi by Text");
select.selectByVisibleText("Audi");

//Get the list of selected options
System.out.println("The selected values in the dropdown options are -");

List<WebElement> selectedOptions = select.getAllSelectedOptions();

for(WebElement selectedOption: selectedOptions)
System.out.println(selectedOption.getText());

// Deselect the value "Audi" by Index
System.out.println("DeSelect option Audi by Index");
select.deselectByIndex(3);

//Deselect the value "Opel" by visible text
System.out.println("Select option Opel by Text");
select.deselectByVisibleText("Opel");

//Validate that both the values are deselected
System.out.println("The selected values after deselect in the dropdown options are -");
List<WebElement> selectedOptionsAfterDeselect = select.getAllSelectedOptions();

for(WebElement selectedOptionAfterDeselect: selectedOptionsAfterDeselect)
System.out.println(selectedOptionAfterDeselect.getText());

//Step#8- Deselect all values
select.deselectAll();
}

driver.quit();
}
}

Run Selenium Tests on BrowserStack Automate

  • Automate provides a reliable Selenium testing infrastructure that becomes highly accelerated by supporting parallel testing of more than 10x of your test suite.
  • It facilitates the debugging with video recordings, automated screenshots of errors, text logs, console logs, and network logs.
  • Run the tests within a highly secured environment.

Access Cloud Selenium Grid

How To Handle Dropdowns in Selenium Python Without Select Class?

You can handle dropdowns in Selenium Python without using the Select class by directly interacting with the dropdown elements. Here’s how:

1. Using Click and Send Keys

If the dropdown is not a traditional <select> element but a custom dropdown built with divs or spans, you might be unable to use the Select class. When that’s the case, try clicking on the dropdown and then sending keys to it.

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC




# Initialize your WebDriver

driver = webdriver.Chrome()




# Navigate to your webpage

driver.get("your_web_page_url")




# Click on the dropdown

dropdown = WebDriverWait(driver, 10).until(

    EC.element_to_be_clickable((By.CSS_SELECTOR, "your_dropdown_css_selector"))

)

dropdown.click()




# Send keys to the dropdown (this might not work for all types of custom dropdowns)

# You might need to inspect the dropdown's HTML to find the right element to send keys to

dropdown_option = WebDriverWait(driver, 10).until(

    EC.element_to_be_clickable((By.CSS_SELECTOR, "your_dropdown_option_css_selector"))

)

dropdown_option.click()




# Alternatively, you can try sending keys directly to the dropdown

# dropdown.send_keys("Your Option")




# Close the WebDriver

# driver.quit()

2. Using ActionChains

In scenarios like dealing with hover-based dropdowns, you can use ActionChains.

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.common.action_chains import ActionChains




# Initialize your WebDriver

driver = webdriver.Chrome()




# Navigate to your webpage

driver.get("your_web_page_url")




# Move to the dropdown

dropdown = driver.find_element(By.CSS_SELECTOR, "your_dropdown_css_selector")

actions = ActionChains(driver)

actions.move_to_element(dropdown).perform()




# Click on the dropdown option

dropdown_option = driver.find_element(By.CSS_SELECTOR, "your_dropdown_option_css_selector")

dropdown_option.click()




# Close the WebDriver

# driver.quit()

3. Directly Using JavaScript

In some cases, using JavaScript can be a straightforward solution, especially when the dropdown is heavily customized or uses shadow DOM.

from selenium import webdriver

from selenium.webdriver.common.by import By




# Initialize your WebDriver

driver = webdriver.Chrome()




# Navigate to your webpage

driver.get("your_web_page_url")




# Click on the dropdown option using JavaScript

dropdown_option = driver.find_element(By.CSS_SELECTOR, "your_dropdown_option_css_selector")

driver.execute_script("arguments[0].click();", dropdown_option)




# Close the WebDriver

# driver.quit()

Why use BrowserStack Automate for Selenium Tests?

Here are reasons why you should use BrowserStack Automate for Selenium Tests:

  • Parallel Testing: BrowserStack Automate lets you test on multiple device and browser combinations at once, speeding up test execution and providing quick feedback.
  • Real Devices and Browsers: Testing on real devices and browsers ensures accurate performance insights, unlike emulators. You can test on the latest devices without buying them.
  • Dedicated Dashboard: Automate offers a dashboard to track and manage your tests, showing test statuses (Pass/Fail/Pending), device details, test duration, screenshots, and more.
  • Custom Reports with Artifacts: Generate detailed, customized reports including test status, device/browser configurations, video recordings, and screenshots.
  • Easy Integration with CI/CD: Seamlessly integrate with CI/CD tools like Jenkins, TeamCity, and TravisCI for faster, reliable, and consistent application delivery.

Talk to an Expert

Conclusion

You can effectively handle dropdowns in Selenium Python using the Select class for standard <select> elements or with manual clicks for custom dropdowns.

The Select class provides a clean way to select options by text, value, or index. For non-standard dropdowns, using Selenium’s basic click-and-find methods is necessary.

BrowserStack, with its real device cloud, allows you to run and test these dropdown interactions across real browsers and devices, ensuring your automation works seamlessly across environments.

Try BrowserStack Now

Useful Resources for Selenium Python

Tags
Automation Testing Selenium

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord