C#Selenium 2:从另一个IList做一个IList

时间:2015-08-13 21:36:46

标签: c# selenium-webdriver

我有一个表中的行列表,我想从第一个列表中创建另一个包含某些行的列表。

我的代码是:

public IWebElement InvoiceTable { get { return Driver.FindElement(By.Id("MainContent_gvInvoices")); } }
public IList<IWebElement> InvoiceRows { get { return InvoiceTable.FindElements(By.CssSelector("tbody tr")); } }
public IList<IWebElement> ACInvoiceRows { get; set; }

public void test()
{
    foreach(IWebElement row in InvoiceRows)
    {
        if(row.Text.Contains("AC"))
        {
            ACInvoiceRows.Add(row);
        }
    }
    Console.WriteLine(ACInvoiceRows.Count);
}

这会引发NullReferenceExcpetion

  

对象引用未设置为对象的实例。

我在这里做错了什么?

2 个答案:

答案 0 :(得分:0)

在以下行中,您不会检查row.Text是否为null

if (row.Text.Contains("AC"))

如果row.Textnull,您最终会得到NullReferenceException。这样做是为了检查null案例。

if (row.Text != null && row.Text.Contains("AC"))

编辑:

ACInvoiceRows也可能没有设置。如果不是,则在您为其指定实际对象之前无法使用它,例如:

public void test()
{
  //Initiate the collection before using it.
  ACInvoiceRows = new List<IWebElement>();

  foreach(IWebElement row in InvoiceRows)
  {
      if(row.Text.Contains("AC"))
      {
          ACInvoiceRows.Add(row);
      }
  }
  Console.WriteLine(ACInvoiceRows.Count);
}

答案 1 :(得分:0)

确保按以下步骤初始化您的驱动程序:

IWebDriver Driver = new ChromeDriver();