c# - 在 Selenium Webdriver 中读取分页数据网格

标签 c# selenium datagrid

我在 Selenium 中不断收到此异常 ...

OpenQA.Selenium.StaleElementReferenceException: 'stale element reference: element is not attached to the page document (Session info: chrome=60.0.3112.113) (Driver info: chromedriver=2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT 10.0.15063 x86_64)'

这太令人沮丧了,我不明白为什么我在下面的 BuildOrg 方法中的 return 语句中抛出异常。

这是触发问题的代码......

for (int i = 0; i <= lastPage; i++)
{
    orgs.AddRange( 
        browser
            .FindElement(By.Id("all_organizations"))
            .FindElement(By.TagName("tbody"))
            .FindElements(By.TagName("tr"))
            .Select(e => BuildOrg(e))
    );

    browser
        .FindElement(By.Id("all_organizations_next"))
        .FindElement(By.TagName("a"))
        .Click();
}

 .....


Organisation BuildOrg(IWebElement orgElement)
{
    var cells = orgElement.FindElements(By.TagName("td"));
    var avatarUrl = cells[0].FindElement(By.TagName("img")).GetAttribute("src");
    var c = DateTimeOffset.Parse(cells[2].Text);
    return new Organisation
    {
        Id = int.Parse(avatarUrl.Split('_')[1].Split('/')[0]),
        Avatar = avatarUrl,
        Name = cells[1].Text,
        Link = cells[1].FindElement(By.TagName("a")).GetAttribute("href"),
        CreatedOn = c
    };
}

任何人都可以对此有所了解吗?

最佳答案

其中一行可能正在两个 .FindElement(s) 之间更新。如果页面已更新或 DOM 元素已被替换,Web 元素将不再可用。

这可能是因为 .Click 之后的第二次迭代开始,即使行尚未刷新。

要克服这个问题,请尝试使用单个 .FindElement(s) 并等待一个元素在 Click 之后变得陈旧:

for (int i = 0; i <= lastPage; i++)
{
    var rows = browser
      .FindElements(By.CssSelector("#all_organizations tbody tr"));

    orgs.AddRange(rows.Select(e => BuildOrg(e)));

    var link = browser
      .FindElement(By.CssSelector("a"))

    link.Click();

    new WebDriverWait(browser, TimeSpan.FromSeconds(3))
      .Until(ExpectedConditions.StalenessOf(rows[0]));
}

关于c# - 在 Selenium Webdriver 中读取分页数据网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46414770/

相关文章:

c# - WPF MediaElement 应用的播放列表

java - Selenium Webdriver 循环

python - 将 chromedriver 与 Selenium 结合使用时,如何纠正超时错误?

单击行时未引发 Silverlight DataGrid MouseLeftButtonDown 事件

c# - WPF 样式按钮 MouseOver 问题

c# - 元素不允许错误 itextSharp

c# - 查询 C# 命名空间和使用

python - 您如何在自动登录脚本中使用浏览器保存的凭据

c# - 使用 foreach 遍历 WPF DataGrid

wpf - 不合理的 WPF DataGrid 加载时间