2

I am using C# selenium web driver for some automation purpose in visual studio.When i run my code sometimes it is working perfectly,but sometimes it is throwing an error "Exception has been thrown by the target of an invocation".When i restart my system it is working fine,again it is showing error after multiple runs.It is happening while giving password after username.The webpage is like username,submit button,password,submit button to login in to website.Without giving password,it is clicking submit button again.

Code where exception occuring

if (ConfigurationManager.AppSettings["IsEncrypted"].ToLower() =="true")
                {

                    UserName.SendKeys(ConfigurationManager.AppSettings["UserName"]);
                    Submit.Click();
                    Thread.Sleep(2000);
                    Password.SendKeys(Base64Decode(ConfigurationManager.AppSettings["Password"]));
                    Submit.Click();
                }

This is the exception

  Exception occured:Exception has been thrown by the target of an invocation.
        Exception occured:Exception has been thrown by the target of an invocation.
        Exception occured System.Reflection.TargetInvocationException: Exception has bee
        n thrown by the target of an invocation. ---> OpenQA.Selenium.StaleElementRefere
        nceException: stale element reference: element is not attached to the page docum
        ent
          (Session info: chrome=58.0.3029.110)
          (Driver info: chromedriver=2.25.426923 (0390b88869384d6eb0d5d09729679f934aab9e
        ed),platform=Windows NT 6.1.7601 SP1 x86_64)
           at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response erro
        rResponse)
           at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecu
        te, Dictionary`2 parameters)
           at OpenQA.Selenium.Remote.RemoteWebElement.Click()
           --- End of inner exception stack trace ---
           at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments,
         Signature sig, Boolean constructor)
           at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Objec
        t[] parameters, Object[] arguments)
           at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invoke
        Attr, Binder binder, Object[] parameters, CultureInfo culture)
           at OpenQA.Selenium.Support.PageObjects.WebDriverObjectProxy.InvokeMethod(IMet
        hodCallMessage msg, Object representedValue)
           at OpenQA.Selenium.Support.PageObjects.WebElementProxy.Invoke(IMessage msg)
           at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgDa
        ta, Int32 type)
           at OpenQA.Selenium.IWebElement.Click()
           at JiraExtract.PageObjects.LoginPage.LoginToApplication() in C:/Program.cs:line 72
           at JiraExtract.Automation.AutomationTest() in c:/Program.cs:line 80
           at JiraExtractor.Program.Main(String[] args) in c:/Program.cs:line 14
8
  • I assume that the error is at Submit.Click();. Why do you need to click twice? Does the error occur at the 2nd submit? Commented Jul 12, 2017 at 12:06
  • Website is designed like that.First i need to give username submit it then i should give password and submit again,to login.Error as i can see"after giving username without giving password it is clicking submit again". Commented Jul 12, 2017 at 12:10
  • Is Password in your code a static class or a WebElement? Commented Jul 13, 2017 at 3:45
  • It is a webElement. Commented Jul 13, 2017 at 3:52
  • Can you try to send text instead of the string from decoder? e.g. Password.SendKeys("just testing");. Can the script click on the submit after enter this password? Commented Jul 13, 2017 at 4:04

3 Answers 3

2

I assume you are using PageObject factory for initializing your Web elements.

As you can notice that your first Submit.Click(); executed without any errors, but when you enter username and try to click on Submit button again, it throws a Stale Element Exception.

Stale Element exception is generated when :

  • The element has been deleted entirely

  • The element is no longer attached to the DOM

In your case, I suppose that you page will Submit button is being detached from DOM and reattached when you enter username.

Solution: Try calling the PageFactory.initElements(getDriver(), ClassWhichHasSubmitButton.class);

Edit: You should call this after you enter your password and before clicking on submit buttonPageFactory.initElements(getDriver(), ClassWhichHasSubmitButton.class);

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

Comments

1

What @Rameshwar told is true.Submit button is detached from DOM.

Solution: Don't click the submit button directly,instead find till the element found and then click.

  {   
   Password.SendKeys(Base64Decode(ConfigurationManager.AppSettings["Password"]));
    Click(By.Id("login-submit"));
   }


 public bool Click(By by)
        {
           bool status = false;
           int i = 0;
           while (i==0) 
           try
           {
             driver.FindElement(by).Click();
             status = true;
             break;
           }
           catch (StaleElementReferenceException e)
           {
           }
           return status;
        }

Comments

0

'Stale element reference error' occurs when you first get moved to the next page and then you try to find out the corresponding element. To avoid this error,you have to first create a new web element and then apply the findElement method because the DOM gets changed as you click the next page link available on the current page.

int count=0;

// **Initial web element**

WebElement element= driver.findElement(By.xpath("//*[@id=\"mainC\"]/h3/a[3]/b"));   

try {
    while (element.isDisplayed()) {             
        Thread.sleep(2000);
        int a1= driver.findElements(By.xpath("//*[@id=\"mainC\"]/ul[1]/li")).size();
        System.out.println(a1);

        element.click();            
        count = a1+count;   

  // **New web element to avoid this error**

    WebElement element1= driver.findElement(By.xpath("//*[@id=\"mainC\"]/h3/a[3]/b"));
    element=element1;           
    }

} catch (Exception e) {

    //e.printStackTrace();
}

Comments

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.