0

Hi Everyone I was trying to make a Selenium Script to verify the validations on Username and Password Text Box by fetching the data from Excel file (.xlt format) but whenever i am running my code it is getting the following error after successful loop run . The code is as follows :

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();
    }

}

And I am getting the following error after first successful loop run :

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

Could any one Explain why I am getting this error and how it can be fixed

1

1 Answer 1

0

That's because you change page in your test, thus your element references break. Have a look at WebDriverExtensions. This framework provides method on opening your links in new windows without invalidating references of WebElements, and enables dynamic lookup of your elements.

Alternatively, if you don't want to use this framework, you could re-search for your elements in your loop like this:

//...
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();

}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi I tried doing what you suggested but I am still getting the same error.
Please paste the error (with exception stack trace) on Pastebin and link it in a comment. If the file in the question isn't original one (stack trace says error happened in 55 line of your file, but the posted file has blank 55 line), please post it in the Pastebin too.
Hi this is the link to the latest code I have tried pastebin.com/Javy8cU1 while the error I am getting now is same and can be found here pastebin.com/LAsXmFvy
@UMANGBHATIA See my updated answer. The problem occurred because you tried to clear inputs after changing page (logging in), thus your emailTextBox and pwdTextBox were invalidated. Remember to always re-find elements if the page changes or reloads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.