为什么我在下面给出的代码中出现 org.openqa.selenium.StaleElementReferenceException 异常?

Why am I getting org.openqa.selenium.StaleElementReferenceException exception in my code given below?

大家好,我试图制作一个 Selenium 脚本,通过从 Excel 文件(.xlt 格式)中获取数据来验证用户名和密码文本框的有效性,但每当我 运行在我的代码中,它在成功循环 运行 后出现以下错误。代码如下:

package com.selenium.com.selenium.practise;

import org.testng.annotations.Test;

import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.testng.annotations.BeforeMethod;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;

public class MultipleCasesUsingExcel {
    public static WebDriver driver = null;

    @Test
    public void Test() throws BiffException, IOException, InterruptedException {
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

        // Clicking on My Account Link
        driver.findElement(By.xpath("//*[@id='top']/body/div/div/div[3]/div/div[4]/ul/li[1]/a")).click();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        WebElement emailTextBox = driver.findElement(By.xpath("//input[@id='email']"));
        WebElement pwdTextBox = driver.findElement(By.xpath("//input[@id='pass']"));
        WebElement loginBtn = driver.findElement(By.xpath("//button[@id='send2']"));

        Workbook book = Workbook.getWorkbook(new File("C:\Users\Umang Bhatia\Documents\data.xlt"));
        Sheet sheet = book.getSheet(0);

        for (int i = 0; i < sheet.getRows(); i++) {
            for (String handle : driver.getWindowHandles()) {
                driver.switchTo().window(handle);
            }
            for (int j = 0; j < sheet.getColumns() - 1; j++) {

                emailTextBox.sendKeys(sheet.getCell(j, i).getContents());
                pwdTextBox.sendKeys(sheet.getCell(j + 1, i).getContents());
                loginBtn.click();
                emailTextBox.clear();
                pwdTextBox.clear();

            }
            Thread.sleep(3000);

        }

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    @BeforeMethod
    public void beforeMethod() {
        System.setProperty("webdriver.chrome.driver",
                "C:\Users\Umang Bhatia\Documents\Selenium Drivers\chrome driver\chromedriver.exe");
        driver = new ChromeDriver();
        driver.navigate().to("http://live.guru99.com/index.php/");
    }

    @AfterMethod
    public void afterMethod() {
        driver.quit();
    }

}

并且在第一次成功循环 运行 后出现以下错误:

[RemoteTestNG] detected TestNG version 6.13.1
Starting ChromeDriver 2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f) on port 36887
Only local connections are allowed.
log4j:WARN No appenders could be found for logger (org.apache.http.client.protocol.RequestAddCookies).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
FAILED: Test
org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document
  (Session info: chrome=63.0.3239.132)
  (Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.10586 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 31 milliseconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:55:52'
System info: host: 'DESKTOP-59DNS54', ip: '192.168.2.5', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_121'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities [{applicationCacheEnabled=false, rotatable=false, mobileEmulationEnabled=false, networkConnectionEnabled=false, chrome={chromedriverVersion=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f), userDataDir=C:\Users\UMANGB~1\AppData\Local\Temp\scoped_dir13984_1984}, takesHeapSnapshot=true, pageLoadStrategy=normal, databaseEnabled=false, handlesAlerts=true, hasTouchScreen=false, version=63.0.3239.132, platform=XP, browserConnectionEnabled=false, nativeEvents=true, acceptSslCerts=true, locationContextEnabled=true, webStorageEnabled=true, browserName=chrome, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true, setWindowRect=true, unexpectedAlertBehaviour=}]
Session ID: eb78d1ac176166bdaa86da5dc12e09c0
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
    at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
    at org.openqa.selenium.remote.RemoteWebElement.clear(RemoteWebElement.java:139)
    at com.selenium.com.selenium.practise.MultipleCasesUsingExcel.Test(MultipleCasesUsingExcel.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
    at org.testng.internal.Invoker.invokeMethod(Invoker.java:571)
    at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:707)
    at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:979)
    at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
    at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
    at org.testng.TestRunner.privateRun(TestRunner.java:648)
    at org.testng.TestRunner.run(TestRunner.java:505)
    at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
    at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
    at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
    at org.testng.SuiteRunner.run(SuiteRunner.java:364)
    at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
    at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
    at org.testng.TestNG.runSuitesSequentially(TestNG.java:1187)
    at org.testng.TestNG.runSuitesLocally(TestNG.java:1116)
    at org.testng.TestNG.runSuites(TestNG.java:1028)
    at org.testng.TestNG.run(TestNG.java:996)
    at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
    at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
    at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)


===============================================
    Default test
    Tests run: 1, Failures: 1, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================

任何人都可以解释为什么我会收到此错误以及如何修复它

那是因为您在测试中更改了页面,因此您的元素引用中断了。看看 WebDriverExtensions。此框架提供了在新 windows 中打开链接的方法,而不会使 WebElements 的引用无效,并启用元素的动态查找。

或者,如果您不想使用这个框架,您可以像这样在循环中重新搜索您的元素:

//...
for (int j = 0; j < sheet.getColumns() - 1; j++) {

    // add these lines
    emailTextBox = driver.findElement(By.xpath("//input[@id='email']"));
    pwdTextBox = driver.findElement(By.xpath("//input[@id='pass']"));
    loginBtn = driver.findElement(By.xpath("//button[@id='send2']"));

    // clear inputs before login. After you click loginBtn, the page 
    // changes, and references of WebElements are invalidated, 
    // thus your emailTextBox.clear(); methods threw  anexception
    emailTextBox.clear();
    pwdTextBox.clear();
    emailTextBox.sendKeys(sheet.getCell(j, i).getContents());
    pwdTextBox.sendKeys(sheet.getCell(j + 1, i).getContents());
    loginBtn.click();

}