异常:org.openqa.selenium.StaleElementReferenceException:过时的元素引用:元素未附加到页面文档

Exception: org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

当我尝试检查警报是否显示时,它显示陈旧元素引用异常。 我已使用以下所有技术来处理警报对话框,但它显示异常。

  1. JS 执行器
  2. 机器人class
  3. WebDriver 等待
  4. .click() 方法
  5. 操作class

我手动检查时所有元素都存在。当我自动化它时,它显示异常... 但我不知道它发生在哪里??!...

步骤定义代码:

(在这段代码中,我使用的是 Action class)

 public void alert_msg_display() throws Throwable {
        WebElement x= driver.findElement(By.xpath("//button[@data-hover='LOGIN NOW']")); //Login button path
        actionClick(driver, x);
        WebElement y= driver.findElement(By.xpath("//md-dialog[@aria-label='Alert']/md-dialog-content/div")); // Alert message text path
        String a= y.getText();
        WebElement z= driver.findElement(By.xpath("//button[@ng-click='hide()']")); // Alert box close button path
        actionClick(driver, z);
        String a1 = "Please Enter Branch Id";
        driver.findElement(By.xpath("//input[@ng-model='Branchid']")).sendKeys("HO");
        actionClick(driver, x);
        String b= y.getText();
        actionClick(driver, z);
        String b1 = "Please Enter Username (Email Id)";
        driver.findElement(By.xpath("//input[@ng-model='Username']")).sendKeys("testmail"); 
        actionClick(driver, x);
        String c= y.getText();
        actionClick(driver, z);
        String c1 = "Please Enter Username (Email Id)";
        driver.findElement(By.xpath("//input[@ng-model='Username']")).clear();
        driver.findElement(By.xpath("//input[@ng-model='Username']")).sendKeys("xxxxx.rt@yyyyy.com");
        actionClick(driver, x);
        String d= y.getText();
        actionClick(driver, z);
        String d1 = "Please Enter Password";
        driver.findElement(By.xpath("//input[@name='password']")).sendKeys("abcde");
        actionClick(driver, x);
        String e= y.getText();
        actionClick(driver, z);
        String e1 = "LOGIN FAILED, PLEASE CHECK YOUR USERNAME OR PASSWORD";
       if (a.equals(a1) && b.equals(b1) && c.equals(c1) && d.equals(d1) && e.equals(e1))
            test.log(LogStatus.PASS, "Test Case ID: LOG_006 to LOG_010 - Pass");
        else
            test.log(LogStatus.FAIL, "Test Case ID: LOG_006 to LOG_010 - Fail");
    }

运行程序文件代码

public void actionClick(WebDriver driver, WebElement a) {
    Actions action = new Actions(driver);
    action.moveToElement(a).click().build().perform();
}

您点击'Login Now' (x) 元素的移动将刷新对 x & y 的引用。因此,您不能使用指向旧引用的 x 和 y,这将导致 Statle Element 异常。

解决方案是每次要单击 x 和 y 时都获取元素,这样您将获得对元素的最新引用。