简体   繁体   中英

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

I am using Selenium to get all text from a table.

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.

Have any method to resolve this? Thanks, everybody.

UPDATED:

I'm want to get result variable because I get all item contains <tr> .

So, I changed to.

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

What you need to use is AddRange method of a List .

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.

On the side note, if you are in ReadOnlycollection , you could do this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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