如何使用C#将所有元素放入Selenium的列表或字符串中?

Eri*_*rik 4 c# selenium list selenium-webdriver

我已经尝试过使用WebElement(和IWebElement)和字符串列表,但我一直在收到错误.如何通过classname获取所有元素文本的列表或字符串?我有所有Selenium参考.我需要一些java.util dll吗?

我应该实现foreach循环吗?

IList<IWebElement> all = new IList<IWebElement>();
all = driver.FindElements(By.ClassName("comments")).Text;
Run Code Online (Sandbox Code Playgroud)

错误:无法创建抽象类或接口'System.Collections.Generic.IList'的实例

错误:'System.Collections.ObjectModel.ReadOnlyCollection'不包含'Text'的定义,也没有扩展方法'Text'接受类型的第一个参数

Ric*_*ard 10

你可以得到这样的所有元素文本:

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;
}
Run Code Online (Sandbox Code Playgroud)


Arr*_*ran 8

虽然您已经接受了答案,但可以使用LINQ来压缩它:

List<string> elementTexts = driver.FindElements(By.ClassName("comments")).Select(iw => iw.Text);
Run Code Online (Sandbox Code Playgroud)

  • @arran我最近尝试过这个,发现我需要像这样构造它:`List <string> elementTexts = new List <string>(driver.FindElements(By.ClassName("comments")).选择(iw => iw.Text));`由于转换问题. (2认同)