c# - Selenium C# - StaleElementReferenceException - 即使在刷新页面之后
问题描述
我收到 OpenQA.Selenium.StaleElementReferenceException ,这有点奇怪,因为我正在刷新页面。所以这里是细节:
我们使用的技术是 React。浏览器:Chrome(最新版本)C# 和 Selenium Webdriver (3.X)
我们有一个带有李项目的左侧菜单。在第一次加载页面时,我可以使用 xpath 单击左侧菜单项,它工作正常。左侧菜单会自行调整,以使该项目不再出现在其中。我认为这会更新 DOM。好的,现在当我尝试单击下一项时,我得到了过时的引用异常。所以我做了以下事情: 1- 刷新页面并双击/单击 - 不起作用 2- 导航到另一个页面并返回此页面并双击/单击 - 不起作用 3- 添加 thread.sleep - 起作用不起作用 4- 捕获异常并尝试再次找到该元素 - 不起作用。
有什么我想念的吗?这是代码:
Actions actions = new Actions(driver);
string[] ItemNames = { "OrganizationDepartment","Organization"};
foreach (String ItemName in ItemNames)
{
try
{
driver.Navigate().Refresh();
//Thread.Sleep(3000);
IWebElement source = driver.FindElement(By.XPath("//div[contains(text(),'" + ItemName+ "')]"));
actions.MoveToElement(source).Perform(); // this is where i get the exception for second element.
actions.DoubleClick(source).Perform(); // this is where i get the exception if i comment above line
}
catch (StaleElementReferenceException stale)
{IWebElement source = driver.FindElement(By.XPath("//div[contains(text(),'" + ItemName+ "')]"));
actions.DoubleClick(source).Perform(); // this is where i get the exception
}
Here is the HTML:
<div><div draggable="true"><li style="position: relative;">
<i title="OrganizationDepartment"></i>OrganizationDepartment
<a title="Drag Me" style="cursor: grab; position: absolute; right: 0px; top: 5px;">
<button type="button" class="ms-Button ms-Button--icon iconButton root-124" data-is-focusable="true" style="cursor: grab;">
<div class="ms-Button-flexContainer flexContainer-114">
<i data-icon-name="DragObject" class="ms-Button-icon icon-126" role="presentation"></i></div></button></a></li></div></div>
<div><div draggable="true"><li style="position: relative;">
<i title="Organization"></i>Organization
<a title="Drag Me" style="cursor: grab; position: absolute; right: 0px; top: 5px;">
<button type="button" class="ms-Button ms-Button--icon iconButton root-124" data-is-focusable="true" style="cursor: grab;">
<div class="ms-Button-flexContainer flexContainer-114">
<i data-icon-name="DragObject" class="ms-Button-icon icon-126" role="presentation"></i></div></button></a></li></div></div>
解决方案
我找到了解决方案。在循环的第二次迭代中变得陈旧的不是元素而是动作对象。我不得不再次重新创建 Actions 对象,然后执行此操作:NewactionsObject.MoveToElement(source).Perform()
推荐阅读
- c++11 - C++ 标准不提供这种类型的散列。
- dropbox - 如果第一次登录 Dropbox 失败,则获取脚本错误(recaptcha)
- vue.js - 你如何对 vue.js 的顶级 .js 进行单元测试?
- asp.net-core - VS2017社区版的Asp.net核心编译问题
- python - 迭代多个熊猫数据帧很慢
- python - 如何在python中打印字符串变量
- r - list.files() 多次列出文件
- android - Fill a listview from a different class android
- javascript - 限制查看器 js url 在不登录的情况下访问文件
- java - MongoDB存储库-如何注释不是文档的子类?