简体   繁体   English

如何将Selenium中的IWebElement添加到C#上的List <>()?

[英]How to add IWebElement in Selenium to List<>() on C#?

I am using Selenium to get all text from a table. 我正在使用Selenium从表中获取所有文本。

Tried filter values to reduce the list to easy manipulation. 尝试使用过滤器值来减少列表,以便于操作。 So, I do with this code: 因此,我使用以下代码:

IWebElement baseTable = browser.FindElementById("column2");
ReadOnlyCollection<IWebElement> rowsInTable = baseTable.FindElements(By.XPath("id('oTableContainer_D')/table/tbody/tr"));

List<IWebElement> result;
foreach (IWebElement valuesNew in rowsInTable )
{
    if (valuesNew.FindElements(By.XPath("td")).ToString() == "")
        return;

    if (valuesNew.FindElements(By.XPath("td")).Count == 10)
    {
        result.Add(valuesNew.FindElements(By.XPath("td").ToString()));
    }
    else
    {
        continue;
    }
}

Error is: 错误是:

Because if I using: 因为如果我使用:

ReadOnlyCollection<IWebElement> result; This result does not have any method like Add to Add to a list. 此结果没有任何方法,例如“ Add到列表”。

Have any method to resolve this? 有什么方法可以解决这个问题? Thanks, everybody. 谢谢大家。

UPDATED: 更新:

I'm want to get result variable because I get all item contains <tr> . 我想获取result变量,因为我得到的所有项目都包含<tr>

So, I changed to. 因此,我改为。

.....
result.Add(valuesNew).
.....

What you need to use is AddRange method of a List . 您需要使用List AddRange方法。

result.AddRange(valuesNew.FindElements(By.XPath("td")));

result is a List<IWebElement> and FindElements returns a collection, so you have to use AddRange method to add the collection. 结果是List<IWebElement>FindElements返回一个集合,因此您必须使用AddRange方法添加该集合。

On the side note, if you are in ReadOnlycollection , you could do this. 在旁注中,如果您处于ReadOnlycollection ,则可以执行此操作。

var  readOnlyelements = new ReadOnlyCollection<IWebElement>(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM