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;
}
Question
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
Solution
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;
}
OTHER TIPS
Although you've accepted an answer, it can be condensed using LINQ:
List<string> elementTexts = driver.FindElements(By.ClassName("comments")).Select(iw => iw.Text);
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>();
However, you need .Text
of each IWebElement
, so your list should probably be List<string>
:
IList<string> all = new List<string>();
Use foreach
to add items into your list:
foreach(var element in driver.FindElements(By.ClassName("comments"));
{
all.Add(element.Text);
}
You can do it this way too, and it parses through the menu list and gets the list text.
IWebElement menuOptions;
menuOptions = _browserInstance.Driver.FindElement(By.XPath(".//*[@id='xxxxxxxxxxxxxxxxxx']/ul[2]/li[3]"));
IList<IWebElement> list = menuOptions.FindElements(By.TagName("li"));
//// get the column headers
char[] character = "\r\n".ToCharArray();
string[] Split = menuOptions.Text.Split(character);
for (int i = 0; i < Split.Length; i++)
{
if (Split[i] != "")
{
_log.LogEntry("INFO", "column Text", true,
Split + " Text matches the expected:" + Split[i]);
}
}
I have used this form
public List<string> GetValidations()
{
IList<IWebElement> elementList = _webDriver.FindElements(By.Id("validationList")); // note the FindElements, plural.
List<string> validations = new List<string>();
foreach (IWebElement element in elementList)
{
validations.Add(element.ToString());
}
return validations;
}