简体   繁体   English

C# Selenium 无法点击微软登录的登录按钮

[英]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 OpenQA.Selenium.StaleElementReferenceException:过时的元素引用:元素未附加到页面文档

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.得到StaleElementReferenceException的原因是驱动程序找到了该元素,但此时页面刷新,您尝试对其进行交互,因此元素 state 是陈旧的。

Try to initialize the element signInbtn1 after you fill the password field:填写密码字段后尝试初始化元素signInbtn1

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.我没有将 C# 用于测试脚本,但我通过 javascript 调用 selenium 驱动程序(在开玩笑的测试中),并且对于您提到的特定登录模式遇到了同样的问题。

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.查看开发工具中的 HTML,我发现在使用 ID(“ idSIButton9" )时存在一个微妙的问题,因为一旦输入 email,按钮元素就会发生变化。即。 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.我发现使用 id 两次来标识相同的按钮元素会导致元素陈旧问题。 So, for the second time round, I found the button element using the following xpath因此,第二次,我使用以下 xpath 找到了按钮元素

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

This is much more specific than the id in this case.在这种情况下,这比 id 更具体。

Hope that helps.希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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