Having an HTML dropdown on a web page, i would like to select, via Selenium, an element from it, or deselect the selected one.
An example of an HTML representation of a dropdown can be found below – it displays a list of winter months:
<select id="winter"> <option value="Dec">December</option> <option value="Jan">January</option> <option value="Feb">February</option> </select>
This element would look something like:
The task is to easily select / deselect an element from the dropdwon.
First of all, you must import the class that offers the support for the dropdown, from the Selenium library:
Then, you must initialize an instance of type Select. This is the Selenium representation of an HTML dropdown element. Declaring such an element can be done as follows – by providing the webElement that identifies the dropdown on the page (as per the CSS and XPATH articles found on this blog, you can identify the element by some unique property, like maybe an id or a class – please refer to the corresponding articles):
private Select dropdown = new Select(CSS_OR_XPATH_SELECTOR);
Above you just passed the webElement selector for the dropdown to the initialization of the Select object.
Now that the dropdown / select has been declared, one can select an element from the dropdown in a few of ways:
- By Value: By looking at the example above, each item from the dropdown is represented by a tag (<option>), and in this example, each such tag also has a “value” attribute. To select an item from the dropdown, you can use the “value” for identifying it, when calling the selectByValue method. For example, to select January from the above dropdown, you can use the following method call:
- By Text: You can choose to specify the text that is displayed in the dropdown to select the item, however this is the least suggested method (as the text can be changed frequently). In order to select, for example, December from the above dropdown, the following command should be used:
- By Index: Here you will only need to pass in the index of the item you want to select from the dropdown – for example, if the dropdown has 3 items, and you want to select the third one, you will pass 2 as parameter for the “selectByIndex” method (as this is an index, it will start from 0). This is a very good identification method when the text that is displayed in the dropdown changes constantly, or the same dropdown is used in different languages. To select February from the above dropdown, use the following command:
Similarly, for deselecting an element, the following methods can be used (these make most sense when the dropdown is of ‘multiple’ type, meaning you can select several options at the same time – after selecting a bunch of them, you would like to only have a couple of them selected):
dropdown.deselectByValue("Jan"); dropdown.deselectByIndex(2); dropdown.deselectByVisibleText("December");