Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of items in Selenium WebDriver using C#

How to write the same piece of code in C# ?

List<WebElement> displayedOptions = driver.FindElements(By.TagName("select"));
for (WebElement option : displayedOptions) 
 {
    if (option.displayed) 
    {
        displayedOptions.Add(option);
    }
 }
like image 207
jessica Avatar asked May 29 '13 16:05

jessica


2 Answers

There is a class created specifically for select HTML elements (i.e. dropdowns).

It is the SelectElement class inside the OpenQA.Selenium.Support.UI namespace.

This is a wrapper around select elements, giving easy access to common things people use/interact with in select elements.

Your example would be translated into (using C# 3 or above, since I'm using LINQ):

IList<IWebElement> selectElements = driver.FindElements(By.TagName("select"));
var displayedSelectElements = selectElements.Where(se => se.Displayed);

It's important to know what this code does. It will first find all select elements and put them into a new list.

It will then filter those out, to only the select elements that are displayed, that is, their .Displayed property is true. This is a direct translation of your example code.

However, you've not really specified what you are trying to do, and I think the example is better suited as this:

var selectElement = new SelectElement(driver.FindElement(By.Id("something")));
var displayedOptions = selectElement.Options.Where(o => o.Displayed);

The above would find a specific select elements, and filter the options within that select to only those that are displayed. Again, that is, have their .Displayed property as true.

Edit

Since the above code is what you need, but you want in the form of a for loop, a similar thing would look like:

var selectElement = new SelectElement(driver.FindElement(By.Id("something")));
var allOptions = selectElement.Options;

for (int i = 0; i < allOptions.Length; i++)
{
    if (allOptions[i].Displayed)
    {
        // do something
        // like add to a new list?
    }
}
like image 151
Arran Avatar answered Sep 17 '22 12:09

Arran


FindElements returns ReadOnlyCollection. So its better to define

ReadOnlyCollection<IWebElement> displayedOptions  = driver.FindElements(By.TagName("select"));

for (WebElement option : displayedOptions) 
{
  if (option.displayed) 
  {
    //displayedOptions.Add(option); //You can't do that
    // do something else
  }
}
like image 45
gtzinos Avatar answered Sep 19 '22 12:09

gtzinos