How to handle dropdown in Selenium Python?

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

Get Started free
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.

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 8

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

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

Tags
Automation Testing Selenium