How to avoid “StaleElementReferenceException” in Selenium?

前端 未结 16 2133
一向
一向 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 13:00

    A solution in C# would be:

    Helper class:

    internal class DriverHelper
    {
    
        private IWebDriver Driver { get; set; }
        private WebDriverWait Wait { get; set; }
    
        public DriverHelper(string driverUrl, int timeoutInSeconds)
        {
            Driver = new ChromeDriver();
            Driver.Url = driverUrl;
            Wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(timeoutInSeconds));
        }
    
        internal bool ClickElement(string cssSelector)
        {
            //Find the element
            IWebElement element = Wait.Until(d=>ExpectedConditions.ElementIsVisible(By.CssSelector(cssSelector)))(Driver);
            return Wait.Until(c => ClickElement(element, cssSelector));
        }
    
        private bool ClickElement(IWebElement element, string cssSelector)
        {
            try
            {
                //Check if element is still included in the dom
                //If the element has changed a the OpenQA.Selenium.StaleElementReferenceException is thrown.
                bool isDisplayed = element.Displayed;
    
                element.Click();
                return true;
            }
            catch (StaleElementReferenceException)
            {
                //wait until the element is visible again
                element = Wait.Until(d => ExpectedConditions.ElementIsVisible(By.CssSelector(cssSelector)))(Driver);
                return ClickElement(element, cssSelector);
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
    

    Invocation:

            DriverHelper driverHelper = new DriverHelper("http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp", 10);
            driverHelper.ClickElement("input[value='csharp']:first-child");
    

    Similarly can be used for Java.

提交回复
热议问题