Handle Dropdown in Selenium Python

Profile picture for user arilio666

In selenium python, dropdowns can be handled and selected from the option using a class called the 'Select' class. Select class is instantiated by using the select tag selector inside the select as an argument. If you spot a select tag in DOM, the select class is the one.

select = Select(dropdown)

The value in the dropdown can be selected using WebDriver's Select class. There are three techniques:

  1. selectByValue
  2. selectByVisibleText
  3. selectByIndex

Here is an example HTML code:

<select id="mySelect">
<option value="option1">One</option>
<option value="option2">Two</option>
<option value="option3">Three</option>
</select>

This can be handled by select class by:

select = Select(dropDown)
select.select_by_visible_text('Three')
select.select_by_index(1)

Example:

Autopract site solely created for handling dropdowns is used, for example, in this site.

  • Let us try to select 'Football' by text and 'Table Tennis' by index.
  • Select's index starts from zero, so Table Tennis is in the third index. Let us check it out using the Selenium code.
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium. web driver.common.keys import Keys
from selenium.webdriver.support.UI import Select

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

driver.maximize_window()
driver.get('http://autopract.com/selenium/dropdown1/')
dropDown = driver.find_element(By.XPATH,"//select[@class='custom-select']")
select = Select(dropDown)
select.select_by_visible_text('Football')
select.select_by_index(3)
  • This code will select Football first and Table Tennis from the dropdown by the third index.
  • This is how we can select from the dropdown in selenium using Python.