How to avoid “StaleElementReferenceException” in Selenium?

前端 未结 16 2389
一向
一向 2020-11-22 12:12

I\'m implementing a lot of Selenium tests using Java. Sometimes, my tests fail due to a StaleElementReferenceException. Could you suggest some approaches to mak

16条回答
  •  时光说笑
    2020-11-22 12:44

    Generally this is due to the DOM being updated and you trying to access an updated/new element -- but the DOM's refreshed so it's an invalid reference you have..

    Get around this by first using an explicit wait on the element to ensure the update is complete, then grab a fresh reference to the element again.

    Here's some psuedo code to illustrate (Adapted from some C# code I use for EXACTLY this issue):

    WebDriverWait wait = new WebDriverWait(browser, TimeSpan.FromSeconds(10));
    IWebElement aRow = browser.FindElement(By.XPath(SOME XPATH HERE);
    IWebElement editLink = aRow.FindElement(By.LinkText("Edit"));
    
    //this Click causes an AJAX call
    editLink.Click();
    
    //must first wait for the call to complete
    wait.Until(ExpectedConditions.ElementExists(By.XPath(SOME XPATH HERE));
    
    //you've lost the reference to the row; you must grab it again.
    aRow = browser.FindElement(By.XPath(SOME XPATH HERE);
    
    //now proceed with asserts or other actions.
    

    Hope this helps!

提交回复
热议问题