Dropdowns are one of the general elements present in any webpage, after buttons and textbars dropdowns are more frequently available element.

Selenium Kotlin provides Select class, with help of select class we can handle dropdowns on the webpage


Steps to select a value in dropdown in selenium kotlin:

  • Find the dropdown using findElement
  • Create object for Select class passing dropdown element as parameter
  • Select the value from the dropdown values

In below example, I am using a method called selectByIndex to select a value from the dropdown.


							
import org.openqa.selenium.By
import org.openqa.selenium.WebElement
import java.util.concurrent.TimeUnit
import org.openqa.selenium.firefox.FirefoxDriver
import org.openqa.selenium.support.ui.Select
fun main(args: Array) {
    // set the geckodriver.exe property
    System.setProperty("webdriver.gecko.driver", "C:/path/geckodriver.exe")
    // open firefox
    val driver = FirefoxDriver()
    driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES)
    // open webpage
    driver.get("https://chercher.tech/java/practice-dropdowns")
    // find the dropdown using xpath
    val dropdownElement = driver.findElement(By.xpath("//select[@id='first']"))
    // create object for Select class
    val dropdown = Select(dropdownElement)
    // select 1st option from the dropdown options
    dropdown.selectByIndex(1)
    Thread.sleep(10000)
}
							

selectByValue()

Methods Present in Select Class ( All methods are non-static )

  • selectByIndex(int index) : selects based on the index of the option, index starts from 0
  • selectByValue(String value) : Sometimes we may need to select a option based on the value attribute, situations like the options may be shuffling or when options are dynamic.
    
    							val dropdownElement = driver.findElement(By.xpath("//select[@id='first']"))
        // create object for Select class
        val dropdown = Select(dropdownElement)
        // select "Apple" value option from the dropdown options
        dropdown.selectByValue("Apple")
    							
  • selectByVisibleText(String text) : Below one is example for selectByVisibleText(), code selects 'Bing' from dropdown
    
     // find the dropdown using xpath
        val dropdownElement = driver.findElement(By.xpath("//select[@id='first']"))
        // create object for Select class
        val dropdown = Select(dropdownElement)
        // select "Apple" value option from the dropdown options
        dropdown.selectByVisibleText("Bing")
    							
  • options : options - property returns all the options present in dropdown irrespective of whether selected or not
    
    // find the dropdown using xpath
    val dropdownElement = driver.findElement(By.xpath("//select[@id='first']"))
    // create object for Select class
    val dropdown = Select(dropdownElement)
    // get all the options and store it in list
    val allElements = dropdown.options
    println("Values present in Single Value Dropdown")
    for (element in allElements) {
    	// iterate over each element and print the text
    	println(element.text)
    }
    println("************************************")
    val dropdownElementMulti = driver.findElement(By.xpath("//select[@id='second']"))
    val dropdownMulti = Select(dropdownElementMulti)
    // get all the options and store it in list
    val allElementsMulti = dropdownMulti.options
    println("Values present in Multi value Dropdown")
    for (elementMulti in allElementsMulti) {
    	// iterate over each element and print the text
    	println(elementMulti.text)
    }
    
  • firstSelectedOption() : returns the selected option from the single dropdown and first selected option from the multi dropdown
    
     // find the dropdown using xpath
        val dropdownElement = driver.findElement(By.xpath("//select[@id='first']"))
        // create object for Select class
        val dropdown = Select(dropdownElement)
        // select 1st selected option from the dropdown options
        val selectedOption = dropdown.firstSelectedOption
        // get the text from the option
        val selectedOptionText = selectedOption.text
        // print the text
        println("Selected option from the dropdown is : $selectedOptionText")
    
  • getAllSelectedOptions() : This function can be applied only on multiple dropdowns and it will retrieve all the options selected in the dropdown.
  • isMultiple() : isMultiple() method will return true if the dropdown is multi value selectable dropdown otherwise false
  • 
    // find the dropdown using xpath
    		WebElement dropdownElement = driver.findElement(By.xpath("//select[@id='second']"));
    		// create object for Select class
    		Select dropdown = new Select(dropdownElement);
    		// check single or multi dropdown
    		boolean singleOrMultiple = dropdown.isMultiple();
    		if (singleOrMultiple) {
    			System.out.println("Dropdown is Multi value dropdown");
    		}else{
    			System.out.println("Dropdown is Single value dropdown");
    		}
    
  • deselectByIndex(int index) : deselectByIndex is applicable on multi-select dropdowns, this will deselect the dropdown option from the selected list of options.
  • 
    // find the dropdown using xpath
        val dropdownElement = driver.findElement(By.xpath("//select[@id='second']"))
        // create object for Select class
        val dropdown = Select(dropdownElement)
        // select options from the dropdown options which have value as 'donut', 'burger','pizza','bonda'
        dropdown.selectByValue("donut")
        dropdown.selectByValue("burger")
        dropdown.selectByValue("pizza")
        dropdown.selectByValue("bonda")
        // deselect a option based on the index (1),
        // be aware that index starts with 0
        dropdown.deselectByIndex(1)
    
  • deselectByValue(String value) : Similar to deselectByIndex you can use deselectByValue
  • deselectByVisibleText(String text) : Similar to deselectByIndex you can use deselectByVisiblText
  • deselectAll() : All will remove all the selected option from multiple select dropdown, you cannot perform this operation on the single value select dropdown.
  • 
    // open webpage
        driver.get("https://chercher.tech//java/practice-dropdowns")
        // find the dropdown using xpath
        val dropdownElement = driver.findElement(By.xpath("//select[@id='second']"))
        // create object for Select class
        val dropdown = Select(dropdownElement)
        // select options from the dropdown options which have text as 'Donut', 'Bonda'
        dropdown.selectByVisibleText("Donut")
        dropdown.selectByVisibleText("Bonda")
        // deselect all the options
        dropdown.deselectAll()
    

Custom Dropdowns

Custom dropdowns are built using different technologies like bootstrap, flask, django so on, but what we receive at our browser is none other than HTML code. These kind of pick and place tools will not follow standard coding but output will be same as original HTML.

Dropdowns are formed using td, button, span, option, submenu tags, so in those cases we cannot use our Select class from the selenium webdriver.

Lets take example : Goto Practice dropdowns page, you can find custom dropdown which uses below HTML code to form the dropdown.


							Custom Dropdown

If you try to use Select class on this custom dropdown, selenium webdriver throws UnexpectedTagNameException

To overcome custom dropdown issue, we have to combine selenium methods to select value from dropdowns which are not formed by using select class.


Common Steps:
1. Click the Dropdown
2. Click the option or the value

Steps to select the Custom Dropdown:

  • Open Browser and Navigate to Url: https://chercher.tech/java/practice-dropdowns
  • Find the custom dropdown box and store it
  • Click the stored dropdown box.
  • // PLEASE DO WRITE IMPORT STATEMENTS
    // click the dropdown element
    dropdownElement.click();
                            	
  • Find the required value from the dropdown and click it, finding option must happen after clicking dropdown
  • 
    // find and click the dropdown element
    driver.findElement(By.xpath("//b[contains(text(),'submenu')]")).click();
                            	

Complete program to choose value from the custom dropdown


							fun main(args: Array) {
    // set the geckodriver.exe property
    System.setProperty("webdriver.gecko.driver", "C:/~/geckodriver.exe")
    // open firefox
    val driver = FirefoxDriver()
    driver.manage().timeouts().implicitlyWait(1, TimeUnit.MINUTES)
    // open webpage
    driver.get("https://chercher.tech/java/practice-dropdowns.php")
    // find the dropdown using xpath
    val dropdownElement = driver.findElement(By.xpath("//button[@id='custom']"))
    // click the dropdown element
    dropdownElement.click()
    Thread.sleep(3000)
    // find and click the dropdown element
    driver.findElement(By.xpath("//b[contains(text(),'submenu')]")).click()
}
							

Verify Particular Option is present in dropdown or not ?

We can verify whether a particular option is present or not in selenium kotlin.

Scenario :
1. Navigate to Selenium webdriver dropdown Practice Page : https://chercher.tech/practice/practice-dropdowns
2. Check 'Avatar' is present under Animals dropdown

Steps to find Option present in dropdown or not in selenium kotlin :

  • Find the dropdown using findElement Method
  • Create object for Select class passing above found element
  • use getOptions() method present in Select class object and store values(it returns webelement in list) in List
  • iterate the list to get the text from the Options one by one
  • compare the result text with expected result.

Example program to verify whether a option is present or not in a dropdonw in kotlin


							
    // find the dropdown using xpath
    val dropdownElement = driver.findElement(By.xpath("//select[@id='animals']"))
    // create object for Select class
    val dropdown = Select(dropdownElement)
    // get all the options and store it in list
    val allElements = dropdown.options
    println("Values present in Single Value Dropdown")
    for (element in allElements) {
        // iterate over each element and print the text
        val dropdownOptionValue = element.text
        if (dropdownOptionValue == "Avatar") {
            println("Avatar Option is present though it is not a cat family :)")
        }
    }
							

Different ways to select dropdown option

Selecting a value from dropdown is easier task but sometimes we may need to select option without using Select class.

We can select the dropdown values in few ways:

  • Select class methods ( selectByIndex, selectByValue, selectByVisibleText )s
  • Click method
    
        // find the dropdown using xpath
        val dropdownElement = driver.findElement(By.xpath("//select[@id='first']"))
        // click the dropdown element
        dropdownElement.click()
        Thread.sleep(3000)
        // find and click the dropdown element
        driver.findElement(By.xpath("//option[text()='Bing']")).click()
    							
  • Actions class click methods
    						
    val act = Actions(driver)
    // click the dropdown
        act.click(driver.findElement(By.xpath("//select[@id='first']")))
                // click the option
                .click(driver.findElement(By.xpath("//option[text()='Bing']")))
                // perform the operation
                .build().perform()	
    
  • Find element method
    						
    // open webpage
        driver.get("https://chercher.tech/java/practice-dropdowns.php")
        // find the option and click it..ta..da
        driver.findElement(By.xpath("//option[text()='Bing']")).click()	
    
  • Sendkeys method
    						
    // open webpage
        driver.get("https://chercher.tech/java/practice-dropdowns.php")
        // find the option and click it..ta..da
        driver.findElement(By.xpath("//select[@id='first']")).sendKeys("Bing")
    
  • Javascript method
    	
        // find the dropdown using xpath
        val dropdownElement = driver.findElement(By.xpath("//button[@id='custom']"))
        //cast driver object to JavaScriptExecutor
        val jse = driver as JavascriptExecutor
        // set the dropdown value t0 'Bing' using javascript
        jse.executeScript("arguments[0].value='Bing'", dropdownElement)
    	

Different ways to check whether Option is selected or not in Dropdown with Selenium Webdriver

We can verify whether a option is selected or not in a dropdown using selenium webdriver, and there are different ways to do it.

  • isSelected() method
  • Verify with getFirstSelectedOption()
  • Use getAttribute() method
  • Use JavascriptExecutor Method

About Author

Article is written by Pavan (a) KarthiQ. Well, I am serving notice period in an MNC, Bangalore. I thought to enrich every person knowledge a little, I always have a feeling, when we teach something, we will learn more than what you know. Knowledge is the only thing that doubles when you spend it.

I have also created the reporter for Protractor Jasmine. Use for your projects without any hesitation

You can also share knowledge by Adding a topic here


Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Protractor Training

new tutorial I am starting new Protractor training batch on Weekends. It is two days course from 01-june-2019 to 02-june-2019 based on class room (BANGALORE)

Interested people can confirm the seat by calling to +91 8971673487 or whatsapp to +91 9003381224

Find the course content : View Content