我在 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/