How to select an option of a listbox
The Select class of the Selenium library is very flexible when it comes to selecting an option of a listbox.
It allows an option to be selected
by index
by visible text
by value
Does it matter how the option is selected?
Can we use any of these methods all the time since they all do the same thing?
Or the way the option is selected depends on the context and on what we do?
Let's take these options one by one.
selectByIndex(int index)
means that you select the option with a specific index.
Let's say the 2nd option out of 5.
One thing that you should make sure is that the listbox has actually at least 2 options.
If it has less, the option selection will generate an exception.
Also, if it is important to select a specific option, selecting by index may create problems in the future.
It is possible that the options of the list will be ordered differently.
It is also possible that new options will be added.
In both of these cases, the option that is selected will not be the one that you need.
For these reasons, selectByIndex() is not a great way of selecting an option.
However, one scenario when selectByIndex works good is when you need to select an option of the list without really caring on the text of the option.
selectByVisibleText(String text)
means that you select an option based on the text that is visible to the user.
Selecting an option this way will not work if the option text changes.
Also, if the site supports multiple languages, since the text of the option will be different for each language, selecting the option will be more complex than it should be.
selectByValue(String value)
This is the best way of selecting an option.
First, the value being an attribute of the element, it will be the same for any language.
Second, the value identifies uniquely each option same with the visible text but without being impacted by possible changes in the visible text.
Let's order these methods from best to worst:
selectByValue
selectByVisibleText
selectByIndex
Thanks for reading.