【问题标题】:Selenium C# - StaleElementReferenceException - Even after refreshing the pageSelenium C# - StaleElementReferenceException - 即使在刷新页面之后
【发布时间】:2020-12-08 16:52:09
【问题描述】:

我收到 OpenQA.Selenium.StaleElementReferenceException,这有点奇怪,因为我正在刷新页面。所以这里是细节:

我们使用的技术是 React。 浏览器:Chrome(最新版本) C# 与 Selenium Webdriver (3.X)

我们有一个带有 Li 项目的左侧菜单。在第一次加载页面时,我可以使用 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>

【问题讨论】:

  • 请注意该元素的显示和可点击属性是正确的

标签: c# selenium-webdriver staleelementreferenceexception


【解决方案1】:

我找到了解决方案。在循环的第二次迭代中变得陈旧的不是元素而是动作对象。我不得不再次重新创建 Actions 对象,然后执行以下操作: NewactionsObject.MoveToElement(source).Perform()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-06
    • 2014-09-26
    相关资源
    最近更新 更多