Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium Select Multiple options from dropdown

I have to select multiple values from dropdown [Some Values are hidden, till I scroll down]. I can select multiple options but I think there must be better way of selecting more than one values from dropdown.

  1. I’m using parameterization to pass the value, I would like to select.
  2. If the dropdown isMultiple, I’m going thru for loop to find all options till it find the parameterization value.
  3. I’m calling this method on my test cases
  4. test.selectMulti(“foo”);
  5. test.selectMulti(“fooz”);
  6. I’m able to select both options but I don’t think this is the most optimize way of doing it.

Does anyone knows better way to pass multiple values part of parametrization and select once options are found. Keep in mind some time I might have to select one option, sometime two and sometime more options.

public void selectMulti (String list) {

    WebElement list = driver.findElement(By.id("abc"));
    Select select = new Select(list);

    if (select.isMultiple()) {

        try {
            List<WebElement> optionLists = select.getOptions();
            listFound = false;
            for (int i = 0; i < optionLists.size(); i++) {
                String text = optionLists.get(i).getText();
                if (text.equals(list)) {
                    optionLists.get(i).click();
                    listFound = true; break;
        }
            } if (listFound) {
    Log.pass();
            } else {
    Log.failed();
            }
        }  catch (StaleElementReferenceException e) {
            e.printStackTrace();
        }   

    } else {
    Log.failed();
    }

    }
like image 233
John Smith Avatar asked Sep 26 '26 20:09

John Smith


1 Answers

I would do something more like this. It solves the issues I mentioned in my comment and also cleans up the code a bit and adds some additional error cases. Since the dropdown is a SELECT, you can use the Select related methods, one of which is selectByVisibleText() so you shouldn't have to loop through the OPTIONS and click them.

public void selectMulti(String[] listItems)
{
    Select select = new Select(driver.findElement(By.id("abc")));

    if (listItems.length > 1 && !select.isMultiple())
    {
        Log.fail("The SELECT is not a multiple select but the list provided is larger than 1.");
        return;
    }

    for (String listItem : listItems)
    {
        try
        {
            select.selectByVisibleText(listItem);
        }
        catch (NoSuchElementException e)
        {
            Log.failed(listItem + " was not an available option");
            e.printStackTrace();
            return;
        }
    }
}
like image 129
JeffC Avatar answered Sep 28 '26 11:09

JeffC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!