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

时间:2018-02-11 11:10:33

标签: java selenium selenium-webdriver selenium-chromedriver jxl

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

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
===============================================

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

1 个答案:

答案 0 :(得分:0)

那是因为您在测试中更改了页面,因此您的元素引用了break。看看WebDriverExtensions。此框架提供了在新窗口中打开链接而不会使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();

}