检查表是否包含元素

时间:2019-01-17 09:50:03

标签: c# selenium-webdriver

我有一个测试表的搜索功能的测试。它在表中占据第一行,从该行中获取一些数据,然后将数据输入搜索框。然后,它会再次搜索该表,然后从搜索结果中检查数据是否与搜索前表中的数据匹配。

问题在于,如果找不到数据,则表中没有元素。我的测试代码在此部分代码上引发了超时异常:

//Get search results
var resultRows = table.FindElements(By.TagName("tr"));
//If there are not results, search is not functional
if (resultRows != null && resultRows.Count > 0)
{
    //Iterate through search results
    foreach (var row in resultRows)
    {
        //Get columns for current row
        var resultCols = row.FindElements(By.TagName("td"));
        //If column 'Priceable item' value is different than original data, search is not functional
        if (resultCols[searchColumn].Text != searchData)
        {
            isValid = false;
        }
    }
}
else
{
    isValid = false;
}

return isValid;

一旦我在调试器中到达此行,就会引发异常:

var resultRows = table.FindElements(By.TagName("tr"));

在查找所有元素之前,如何检查表是否包含任何元素?

1 个答案:

答案 0 :(得分:1)

请尝试按以下方式查找TR元素

List<WebElement> resultRows = driver.findElements(By.xpath("//table/tbody/tr"));

//if your table has certain identifier/class
    //List<WebElement> rows = driver.findElements(By.xpath("//table[class='CLASS_NAME']/tbody/tr"));


if (resultRows != null && resultRows.Count > 0)
{
    //Iterate through search results
    foreach (var row in resultRows)
    {
        //Get columns for current row
        var resultCols = row.FindElements(By.TagName("td"));
        //If column 'Priceable item' value is different than original data, search is not functional
        if (resultCols[searchColumn].Text != searchData)
        {
            isValid = false;
        }
    }
}
else
{
    isValid = false;
}

return isValid;