0

I have a simple solution to search for a string within a dropdown menu, but I would like to improve the code so it allows more options, preferable storing each option as a separate entry in a list or array which I can iterate through

I get the contents using this method and assert the string exists:

var dropdown = Driver.FindElement(element);
var dropdownText = dropdown.Text;
Assert.IsTrue(dropdownText.Contains("teststring"));

This method works, however the problem I have is that dropdown.text is just one long string, with each element separated by "\r\n". I have tried to store them in an IList using:

IList<string> elementTexts =  Driver.FindElements(element).Select(a => a.Text).ToList();

But this gave the same results as my current method (one long string stored in a single entry in the list).

Is there a better way to perform this search or store the dropdown strings?

2

If you want every dropdown value in a List, try using this:

    WebElement select = driver.findElement(By.id("selection"));
    List<WebElement> options = select.findElements(By.tagName("option"));
    for (WebElement option : options) {
          // actions on every option, like extracting the value
    }

Alternatively, convert your WebElement el to a SelectElement:

SelectElement dropdown = new SelectElement(el);

The dropdown.Options attribute will get you the same list as above.

0

As an alternative to the answer I accepted above, I'm now using the following code when I need to do this:

var dropdown = Driver.FindElement(element);
var optionList = new List<string>();
optionList = dropdown.Text.Split(new[] { "\r\n" }, StringSplitOptions.None).ToList();

Now I can search within the list for a string to see if it is present in the dropdown.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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