陈旧元素参考例外c#Selenium Webdriver

时间:2017-07-12 10:32:26

标签: c# .net visual-studio-2012 selenium-webdriver automation

我正在使用C#selenium web驱动程序来实现visual studio中的某些自动化目的。当我运行我的代码时,它有时会完美运行,但有时它会抛出一个错误“调用目标引发了异常”。当我重新启动我的系统它运行正常,多次运行后显示错误。在用户名后输入密码时正在发生。网页就像用户名,提交按钮,密码,提交按钮登录网站。没有给密码,它再次点击提交按钮。

发生异常的代码

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

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

这是例外

  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

4 个答案:

答案 0 :(得分:0)

我假设您正在使用PageObject工厂来初始化Web元素。

您可以注意到您的第一个Submit.Click();执行时没有任何错误,但是当您输入用户名并尝试再次点击“提交”按钮时,它会抛出Stale Element Exception

在以下情况下生成陈旧元素异常:

  • 该元素已被完全删除

  • 该元素不再附加到DOM

在您的情况下,我认为当您输入用户名时,您的页面Submit按钮将与DOM分离并重新附加。

解决方案:尝试拨打PageFactory.initElements(getDriver(), ClassWhichHasSubmitButton.class);

修改 您应在输入密码后点击提交按钮PageFactory.initElements(getDriver(), ClassWhichHasSubmitButton.class);

之前拨打此电话

答案 1 :(得分:0)

@Rameshwar告诉的是真的。提交按钮与DOM分离。

解决方案: 不要直接单击提交按钮,而是直到找到元素,然后单击。

  {   
   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;
        }

答案 2 :(得分:0)

SendKeys似乎有问题。改用Actions:

var element = wait.Until(MyCondition(By.Name("j_password")));
Actions actions = new Actions(driver);
actions.Click(element);
actions.SendKeys("123");
actions.Perform();

答案 3 :(得分:0)

“陈旧元素引用错误”会在您首先移至下一页,然后尝试查找相应的元素时发生。 为避免此错误,您必须首先创建一个新的Web元素,然后应用findElement方法,因为当您单击当前页面上的下一页链接时,DOM会更改。

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