【问题标题】:Stale Element Reference Exception c# Selenium Webdriver陈旧元素引用异常 c# Selenium Webdriver
【发布时间】:2019-01-22 14:01:01
【问题描述】:

我在 Visual Studio 中将 C# selenium Web 驱动程序用于某些自动化目的。当我运行我的代码时,有时它运行良好,但有时它会抛出错误“调用目标已抛出异常”。当我重新启动我的系统它工作正常,多次运行后再次显示错误。在用户名后输入密码时发生。网页就像用户名,提交按钮,密码,提交按钮登录到网站。不提供密码,它再次点击提交按钮。

发生异常的代码

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

【问题讨论】:

  • 我假设错误在Submit.Click();。为什么需要点击两次?第二次提交时是否出现错误?
  • 网站是这样设计的。首先我需要给用户名提交然后我应该给密码并再次提交,登录。错误我可以看到“在给用户名而不给密码后点击提交再次”。
  • 你的代码中的Password是静态类还是WebElement?
  • 它是一个 webElement。
  • 您可以尝试发送文本而不是解码器中的字符串吗?例如Password.SendKeys("just testing");。输入这个密码后脚本可以点击提交吗?

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


【解决方案1】:

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

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

在以下情况下会生成 Stale Element 异常:

  • 元素已被完全删除

  • 元素不再附加到 DOM

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

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

编辑: 您应该在输入密码后和点击提交按钮之前调用它PageFactory.initElements(getDriver(), ClassWhichHasSubmitButton.class);

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      “过时元素引用错误”发生在您第一次移动到下一页然后您尝试找出相应的元素时。 为避免此错误,您必须首先创建一个新的 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();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-04
        • 2013-04-16
        • 2017-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多