How To Select from a Dropdown in Selenium Java, Python, Ruby, C#

Yosuva ArulanthuC#, Java, Python, Ruby, Selenium, Test Automation, TestingLeave a Comment

Selecting from a dropdown list seems like one of those simple things. Just grab the list by it’s element and select an item within it based on the text you want.

While it sounds pretty straightforward, there is a bit more finesse to it.

Let’s take a look at a couple of different approaches.

An Example

Java

// filename: Dropdown.java

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

public class Dropdown {
    WebDriver driver;

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
    }

    @After
    public void tearDown() throws Exception {
        driver.quit();
    }
    //gets all the options and clicks if the option is Option 1
    @Test
    public void dropdownTest() {
        driver.get("http://the-internet.herokuapp.com/dropdown");
        WebElement dropdownList = driver.findElement(By.id("dropdown"));
        List<WebElement> options = dropdownList.findElements(By.tagName("option"));
        for (int i = 0; i < options.size(); i++) {
            if (options.get(i).getText().equals("Option 1")) {
                options.get(i).click();
            }
        }
        String selectedOption = "";
        for (int i = 0; i < options.size(); i++) {
            if (options.get(i).isSelected()) {
                selectedOption = options.get(i).getText();
            }
        }
        assertThat(selectedOption, is("Option 1"));
    }
    @Test
    public void dropdownTestRedux() {
        driver.get("http://the-internet.herokuapp.com/dropdown");
        Select selectList = new Select(driver.findElement(By.id("dropdown")));
        selectList.selectByVisibleText("Option 1");
        assertThat(selectList.getFirstSelectedOption().getText(), is(equalTo("Option 1")));
        //in addition to selecting by text you can also select by value.

        selectList.selectByValue("2");
    }

}

Python

# filename: dropdown.py
import unittest
from selenium import webdriver
from selenium.webdriver.support.select import Select as WebDriverSelect
class DropDown(unittest.TestCase):


    def setUp(self):
        self.driver = webdriver.Firefox()

    def tearDown(self):
        self.driver.quit()

    def test_example_1(self):
        driver = self.driver
        driver.get('http://the-internet.herokuapp.com/dropdown')
        dropdown_list = driver.find_element_by_id('dropdown')
        options = dropdown_list.find_elements_by_tag_name('option')
        for opt in options:
            if opt.text == 'Option 1':
                opt.click()
                break
        for opt in options:
            if opt.is_selected():
                selected_option = opt.text
                break
        assert selected_option == 'Option 1', "Selected option should be Option 1"

    def test_example_2(self):
        driver = self.driver
        driver.get('http://the-internet.herokuapp.com/dropdown')
        dropdown = driver.find_element_by_id('dropdown')
        select_list = WebDriverSelect(dropdown)
        select_list.select_by_visible_text('Option 1')
        selected_option = select_list.first_selected_option.text
        assert selected_option == 'Option 1', "Selected option should be Option 1"
        #In addition to selecting by text, you can also select by value.

        select_list.select_by_value('1')

if __name__ == "__main__":
    unittest.main()

Ruby

# filename: dropdown.rb

require 'selenium-webdriver'
require 'rspec/expectations'
include RSpec::Matchers

def setup
  @driver = Selenium::WebDriver.for :firefox
end

def teardown
  @driver.quit
end

def run
  setup
  yield
  teardown
end
run do
  @driver.get 'http://the-internet.herokuapp.com/dropdown'

  dropdown_list = @driver.find_element(id: 'dropdown')
  options = dropdown_list.find_elements(tag_name: 'option')
  options.each { |option| option.click if option.text == 'Option 1' }

  selected_option = options.map { |option| option.text if option.selected? }.join
  expect(selected_option).to eql 'Option 1'
end
run do
  @driver.get 'http://the-internet.herokuapp.com/dropdown'

  dropdown = @driver.find_element(id: 'dropdown')
  select_list = Selenium::WebDriver::Support::Select.new(dropdown)
  select_list.select_by(:text, 'Option 1')

  selected_option = select_list.selected_options[0].text
  expect(selected_option).to eql 'Option 1'
  #In addition to selecting by text, you can also select by value.

  select_list.select_by(:value, '1')
end

C#

// filename: Dropdown.cs
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using System.Collections.Generic;

public class Dropdown
{
    IWebDriver Driver;

    [SetUp]
    public void SetUp()
    {
        Driver = new FirefoxDriver();
    }

    [TearDown]
    public void TearDown()
    {
        Driver.Quit();
    }
    [Test]
    public void SelectFromDropdownTheHardWay()
    {
        Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/dropdown");
        IWebElement Dropdown = Driver.FindElement(By.Id("dropdown"));
        IReadOnlyCollection<IWebElement> DropdownOptions = Dropdown.FindElements(By.TagName("option"));
        foreach(IWebElement Option in DropdownOptions)
        {
            if(Option.Text.Equals("Option 1"))
                Option.Click();
        }
        string SelectedOption = "";
        foreach (IWebElement Option in DropdownOptions)
        {
            if (Option.Selected)
                SelectedOption = Option.Text;
        }
        Assert.That(SelectedOption.Equals("Option 1"));
    }
     [Test]
    public void SelectFromDropdownTheEasyWay()
    {
        Driver.Navigate().GoToUrl("http://the-internet.herokuapp.com/dropdown");
        SelectElement Dropdown = new SelectElement(Driver.FindElement(By.Id("dropdown")));
        Dropdown.SelectByText("Option 1");
        Assert.That(Dropdown.SelectedOption.Text.Equals("Option 1"));
        //in addition to selecting by text you can also select by value.

        Dropdown.SelectByValue("1");
    }

}

This is what happens when you run this code

  • Open the browser
  • Visit the example application
  • Find the dropdown list
  • Select the requested item from the dropdown list
  • Assert that the selected option is the one you expect
  • Close the browser

Leave a Reply

Your email address will not be published.