Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've tried using WebElement (and IWebElement) and string lists, but I keep getting errors. How can I get a list or strings of all the elements text by classname? I have all Selenium references. Do I need some java.util dll?

Should I implement a foreach loop?

IList<IWebElement> all = new IList<IWebElement>();
all = driver.FindElements(By.ClassName("comments")).Text;

Error: Cannot create an instance of the abstract class or interface 'System.Collections.Generic.IList'

Error: 'System.Collections.ObjectModel.ReadOnlyCollection' does not contain a definition for 'Text' and no extension method 'Text' accepting a first argument of type

like image 509
Erik Avatar asked May 11 '14 01:05

Erik


2 Answers

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;
}
like image 57
Richard Avatar answered Oct 20 '22 16:10

Richard


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

List<string> elementTexts = driver.FindElements(By.ClassName("comments")).Select(iw => iw.Text);
like image 22
Arran Avatar answered Oct 20 '22 16:10

Arran