'Unable to click Sign in button of Microsoft Login in C# Selenium

Microsoft Login

Trying to click Sign In button but getting "Stale element Exception error".

IWebElement email = driver.FindElement(By.XPath("//*[contains(@name,'loginfmt')]"));
            IWebElement password = driver.FindElement(By.XPath("//*[contains(@name,'passwd')]"));
            IWebElement signIn = driver.FindElement(By.XPath("//*[contains(@id,'idSIButton9')]"));
            IWebElement signInbtn = driver.FindElement(By.XPath("//*[@id='idSIButton9']"));
            IWebElement signInbtn1 = driver.FindElement(By.XPath("//input[@type='submit']"));
        

        email.SendKeys("[email protected]");
        email.SendKeys(Keys.Enter);
        Thread.Sleep(1000);
        password.SendKeys("Abc*123$");
        password.SendKeys(Keys.Enter);
        signInbtn1.Click(); 

Error:

OpenQA.Selenium.StaleElementReferenceException : stale element reference: element is not attached to the page document



Solution 1:[1]

The reason of getting the StaleElementReferenceException is that the driver have found the element, but the page refreshed by the moment, you try to interract it, so element state is stale.

Try to initialize the element signInbtn1 after you fill the password field:

password.SendKeys("Abc*123$");
password.SendKeys(Keys.Enter);
IWebElement signInbtn1 = driver.FindElement(By.XPath("//input[@type='submit']"));

signInbtn1.Click(); 

Solution 2:[2]

I wasn't using C# for the test script, but I'm calling the selenium driver via javascript (within a jest test) and was getting the same problem for that specific Login Modal you mentioned.

Looking at the HTML in dev tools, I found that there is a subtle issue when using the ID ("idSIButton9") as the button element will change once the email has been entered in. ie. The button element's value will change from 'Next' to "Sign in"

I found that using the id twice to identify the same button element results in the stale element issue. So, for the second time round, I found the button element using the following xpath

"//input[@value='Sign in']"

This is much more specific than the id in this case.

Hope that helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Max Daroshchanka
Solution 2