[c#] How to get all options in a drop-down list by Selenium WebDriver using C#?

I'm new to both C# and Selenium WebDriver.

I know how to select/click on an option in a drop-down list, but I've a problem before that. Since the drop-down list is dynamically generated, I have to get all options/values from the list before running each case.

Is there anyone kindly tell me how to get all values/options from a drop-down list. I'm using IE and I didn't find any class which supports method to get values/options in Selenium.IE namespace for C#.

My example: A list contains several time zones:

<TD>
  <select name = "time_zone">
    <option value "-09:00"><script>timezone.Alaska</script></option>
    <option value "+00:00"><script>timezone.England</script></option>
    <option value "+02:00"><script>timezone.Greece</script></option>
    <option value "+05:30"><script>timezone.India</script></option>
  </select>
<TD>

This is a drop-down list in an IE page and how to get the dynamically generated time zone list?

My code:

IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
List<IWebElement> options = elem.FindElements(By.TagName("option"));

C# just pops an Error: Cannot implicitly covert type 'OpenQA.Selenium.IWebElement' to 'System.Collections.Generic.List'. An explicit conversion exists (are you missing a cast?).

thanks.

This question is related to c# drop-down-menu selenium selenium-webdriver

The answer is


 WebElement element = driver.findElement(By.id("inst_state"));
        Select s = new Select(element);
        List <WebElement> elementcount = s.getOptions();

        System.out.println(elementcount.size());
        for(int i=0 ;i<elementcount.size();i++)
        {
            String value = elementcount.get(i).getText();
            System.out.println(value);

        }

Use IList<IWebElement> instead of List<IWebElement>.

For instance:

IList<IWebElement> options = elem.FindElements(By.TagName("option"));
foreach (IWebElement option in options)
{
    Console.WriteLine(option.Text);
}

Make sure you reference the WebDriver.Support.dll assembly to gain access to the OpenQA.Selenium.Support.UI.SelectElement dropdown helper class. See this thread for additional details.

Edit: In this screenshot, you can see that I can get the options just fine. Is IE opening up when you create a new InternetExplorerDriver? Screenshot


It seems to be a cast exception. Can you try converting your result to a list i.e. elem.findElements(xx).toList ?


Here is code in Java to get all options in dropdown list.

WebElement sel = myD.findElement(By.name("dropdown_name"));
List<WebElement> lists = sel.findElements(By.tagName("option"));
    for(WebElement element: lists)  
    {
        String var2 = tdElement.getText();
        System.out.println(var2);
    }

Hope it may helpful to someone.


You can try using the WebDriver.Support SelectElement found in OpenQA.Selenium.Support.UI.Selected namespace to access the option list of a select list:

IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));

SelectElement selectList = new SelectElement(elem);
IList<IWebElement> options = selectList.Options;

You can then access each option as an IWebElement, such as:

IWebElement firstOption = options[0];
Assert.AreEqual(firstOption.GetAttribute("value"), "-09:00");

To get all the dropdown values you can use List.

List<string> lstDropDownValues = new List<string>();
int iValuescount = driver.FindElement(By.Xpath("\html\....\select\option"))

for(int ivalue = 1;ivalue<=iValuescount;ivalue++)
 {
  string strValue = driver.FindElement(By.Xpath("\html\....\select\option["+ ivalue +"]"));
  lstDropDownValues.Add(strValue); 
 }

You can use selenium.Support to use the SelectElement class, this class have a property "Options" that is what you are looking for, I created an extension method to convert your web element to a select element

public static SelectElement AsDropDown(this IWebElement webElement)
{
    return new SelectElement(webElement);
}

then you could use it like this

var elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));
var options = elem.AsDropDown().Options

WebElement drop_down =driver.findElement(By.id("Category"));
Select se = new Select(drop_down);
for(int i=0 ;i<se.getOptions().size(); i++)
System.out.println(se.getOptions().get(i).getAttribute("value"));

To get all options in a drop-down list by Selenium WebDriver C#:

SelectElement TimeZoneSelect = new SelectElement(driver.FindElement(By.Name("time_zone")));
IList<IWebElement> ElementCount = TimeZoneSelect.Options;
int ItemSize = ElementCount.Count;

for (int i = 0; i < ItemSize; i++)
{
    String ItemValue = ElementCount.ElementAt(i).Text;
    Console.WriteLine(ItemValue);
}

Select select = new Select(driver.findElement(By.id("searchDropdownBox")));

select.getOptions();//will get all options as List<WebElement>

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array How to implement drop down list in flutter? How can I create a dropdown menu from a List in Tkinter? How can I close a dropdown on click outside? Making a drop down list using swift? HTML: Select multiple as dropdown How to get selected value of a dropdown menu in ReactJS Avoid dropdown menu close on click inside Bootstrap 3 dropdown select How to make a drop down list in yii2? Android custom dropdown/popup menu

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java