【问题标题】:Find total count of rows in webtable using xpath in Selenium C#在 Selenium C# 中使用 xpath 查找 webtable 中的总行数
【发布时间】:2019-12-11 10:04:45
【问题描述】:

我正在尝试使用下面的代码从表中查找总行数,但它不起作用。

public IWebElement DocTable => driver.FindElement(By.XPath("//*[@id='ctl00_ContentPlaceHolder1_grdCaseList_DXMainTable']/tbody/tr"));

int RowCount = DocTable.Count(); 

以下是我得到的错误:

错误 CS1061 'IWebElement' 不包含 'Count' 的定义 并且没有可访问的扩展方法“计数”接受第一个参数 可以找到“IWebElement”类型的(您是否缺少使用 指令还是程序集引用?)

【问题讨论】:

    标签: c# selenium selenium-webdriver


    【解决方案1】:

    根据文档FindElement() 使用给定的方法找到第一个IWebElement。其中Count 是一个 List 属性。

    所以要计算所有<tr> 元素的数量,您需要使用FindElements() 创建一个列表,如下所示:

    public ReadOnlyCollection<IWebElement> DocTable => driver.FindElements(By.XPath("//*[@id='ctl00_ContentPlaceHolder1_grdCaseList_DXMainTable']/tbody//tr"));
    int RowCount = DocTable.Count; 
    

    或者

    public IList<IWebElement> DocTable => driver.FindElements(By.XPath("//*[@id='ctl00_ContentPlaceHolder1_grdCaseList_DXMainTable']/tbody//tr"));
    int RowCount = DocTable.Count;
    

    作为替代,

    int RowCount = driver.FindElements(By.XPath("//*[@id='ctl00_ContentPlaceHolder1_grdCaseList_DXMainTable']/tbody//tr")).Count;
    

    注意Count 不是方法而是属性。

    【讨论】:

    • 我仍然收到错误“无法将类型 'OpenQA.Selenium.IWebElement' 隐式转换为 'System.Collections.Generic.List
    • @Gopal 用列表更新了第二个选项,现在应该可以了,第一个选项怎么样?让我知道状态。
    • 使用这两个选项仍然没有成功。现在代码“DocTable.Count”出现错误“字段初始化程序无法引用非静态字段”
    • @Gopal 你能把 keyword public 去掉并重新测试并告诉我状态吗?
    • @Gopal 好吧,代码中有更多变化。能否请您使用新的代码行并再次重新测试?使用当前的代码行,您应该不会看到之前的错误。
    【解决方案2】:

    FindElement 返回一个 IWebElement,在这种情况下是表中的第一行。使用FindElements 获取&lt;tr&gt; 元素的列表

    public List<IWebElement> DocTable => driver.FindElements(By.XPath("//*[@id='ctl00_ContentPlaceHolder1_grdCaseList_DXMainTable']/tbody/tr"));
    

    【讨论】:

      猜你喜欢
      • 2021-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多