How to get all elements into list or string with Selenium using C#? How to get all elements into list or string with Selenium using C#? selenium selenium

How to get all elements into list or string with Selenium using C#?


You can get all of the element text like this:

IList<IWebElement> all = driver.FindElements(By.ClassName("comments"));String[] allText = new String[all.Count];int i = 0;foreach (IWebElement element in all){    allText[i++] = element.Text;}


Although you've accepted an answer, it can be condensed using LINQ:

List<string> elementTexts = driver.FindElements(By.ClassName("comments")).Select(iw => iw.Text);


  1. You can't create an instead of IList<T>, you have to create an instance of class that implements the interface, e.g. List<T>:

    IList<IWebElement> all = new List<IWebElement>();
  2. However, you need .Text of each IWebElement, so your list should probably be List<string>:

    IList<string> all = new List<string>();
  3. Use foreach to add items into your list:

    foreach(var element in driver.FindElements(By.ClassName("comments"));{    all.Add(element.Text);}