How To Select from a Dropdown List in Selenium


647
647 points
select from a dropdown list
select from a dropdown list

How to select from a dropdown list in Selenium

In my entire testing career I have’t worked on an application that doesn’t have a dropdown list. To select from a dropdown list in selenium it’s supposed to be a pretty straight forward job but sometimes might be proven otherwise.

Select from a dropdown list in Selenium Webdriver Java

IWebElement dropDownListBox = driver.findElement(By.Id("locator"));
SelectElement clickThis = new SelectElement(dropDownListBox);
clickThis.SelectByText("UK");

Select from a dropdown list in Selenium Webdriver C#

using OpenQA.Selenium.Support.UI;

 var element = driver.FindElement(By.Id("locator"));
 //create select element object 
 var selectElement = new SelectElement(element);
 //select by value
 selectElement.SelectByValue("Mr Test"); 
 // select by text
 selectElement.SelectByText("MrTestText");

Select from a dropdown list in Selenium Webdriver Ruby

  element = @driver.find_element(id: 'locator')
  options = element.find_elements(tag_name: 'option')
  options.each { |option| option.click if option.text == 'Mr test option' }

  selected_option = options.map { |option| option.text if option.selected? }.join

Select from a dropdown list using Ruby Capybara

Capybara provides a great method to select from a dropdown such as ‘ select ‘ so you can just say:

select 'Mr test'

Another Example using Ruby Capybara

def select(locator, value, type='css')
  find(type.to_sym, locator).find(:option, "#{value}").select_option
end

For more details you check Capybara documentation.

Advertisements

Select from a dropdown list in Selenium Webdriver Python

element = driver.find_element_by_id('selector')
for option in element.find_elements_by_tag_name('option'):
    if option.text == 'Mr test':
        option.click()
        break

You can ajust the code for multiple select:

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

If you want to select a random value from a dropdwon check this out.

Happy testing!


Like it? Share with your friends!

647
647 points
Test engineer

0 Comments

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.