简体   繁体   中英

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

微软登录

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("automate@outlook.com");
        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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM