I have a method below that selects a random item from a dropdown list. This works well mostly, but on occasion it will reselect the default option which is usually "Please Select" or a blank value.

Im looking at how to avoid selecting the default/already selected option.

Below is my code from my Selenium framework.

    public void selectRandomDropDownOption(By dropdownIdentifier, By options) {
    // Putting in a loop to specify number of selections and to then select different values every time.
    for (int i = 0; i < 1; i++) {
        // Click on drop down
        // Get items in dropdown
        List<WebElement> items = driver.findElements(options);
        // Get size of options
        int size = items.size();
        // Generate a random number which will be used to select an item in the list
        int randNo = ThreadLocalRandom.current().nextInt(0, size);

Example of the DOM (fairly standard)

<select name="IPQ_OA_TFINSUP1" id="IPQ_OA_TFINSUP1" onchange="ul_conditional_display_all('FD', 'OA_TFINSUP1');" required="required" class="sv-form-control" aria-invalid="true" aria-describedby="SVb4935443-ae1b-4cf6-357d-57c92b2da566">

<option value="" selected="selected">Please select</option>
<option value="ELCAS">ELCAS</option>
<option value="PROF_AND_CAREER">Professional and Career Development Loan</option> etc....

2 Answers 2


You can simply filter out the invalid options from the list:

List<WebElement> items = driver.findElements(options);
List<WebElement> validItems = items.stream()  
                                     item -> !(
                                              item.getText().equals("Please Select") 
                                              || item.getText().isEmpty())

Despite there is couple of arguable things in your code (like for (int i = 0; i < 1; i++) loop which will be executed a single time) I would suggest to solve your issue before you are entering the method. Your By should incorporate the locator that would not include option with empty value (or take all options except first one).

Hence in your method's code you will be randomly picking from options which do not include default one.

P.S. - if you still need your method to accept all existing options you can do something like this:

int randNo = ThreadLocalRandom.current().nextInt(0, size - 1);
items.get(randNo + 1).click();

This will only require to check a special case when size == 0;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.