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.
We can extract all the options in a dropdown in Selenium with the help of Select class which has the getOptions() method. This retrieves all the options on a Select tag and returns a list of web elements. This method does not accept any arguments.
We can display all items in the list in the dropdown with Selenium webdriver using the Select class. A dropdown is represented by select tag and itsoptions are represented by option tag. To obtain all the list of items we have to use the method getOptions. Its return type is list.
We can retrieve all options in a dropdown using Selenium. All the options in the dropdown are stored in a list data structure. This is achieved with the help of options() which is a method under the Select class. options() returns a list of all options under the select tag.
For Windows: Press the control (ctrl) button to select multiple options. For Mac: Hold down the command button to select multiple options.
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");
Select select = new Select(driver.findElement(By.id("searchDropdownBox")));
select.getOptions();//will get all options as List<WebElement>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With