You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

跳转链接后使用Actions.SendKeys触发Selenium.StaleElementReferenceException问题

Hey Morten, let's figure out why that StaleElementReferenceException is popping up when you try to scroll after switching language pages. Here's the breakdown and actionable fixes:

Why This Happens

When you click the country link (intPageLink.Click()), the browser navigates to a completely new page. This discards the entire DOM from the original page—including any element references or state stored in your static Browser.actions instance. Even though you re-find the footer element in ScrollToFooter(), the existing Actions object still holds stale references to elements from the first page. When you call actions.SendKeys(), it tries to use those invalid references, triggering the error.

Also, your Webpage.Footer getter creates a new Footer instance every time, but it’s still using the same stale Browser.actions object initialized for the initial page.

Fixes to Try

1. Reinitialize Actions After Page Navigation

Since page resets the DOM, you need to refresh your Actions instance to work with the new page. Ditch the static actions variable and create a fresh instance whenever you need it:

public static class Browser {
    public static IWebDriver webDriver;
    // Create a new Actions instance on demand instead of storing it statically
    public static Actions GetActions() {
        return new Actions(webDriver);
    }
    public static void Goto(string url) {
        webDriver.Url = url;
    }
}

Update your Footer class to use this method, and remove the stale Actions parameter from the constructor:

public class Footer {
    private IWebDriver webDriver;
    private IWebElement footer;
    public Footer(IWebDriver webDriver) {
        this.webDriver = webDriver;
    }
    public void GoTo_CountryPageViaFooter(string CountryTag) {
        footer = webDriver.FindElement(By.ClassName("c-footer"));
        var changeCountryButton = footer.FindElement(By.ClassName("c-footer__toggle-country-selector"));
        ScrollToFooter();
        
        var actions = Browser.GetActions();
        actions.MoveToElement(footer).Perform();
        actions.MoveToElement(changeCountryButton).Perform();
        changeCountryButton.Click();

        // Wait for the country selector to load before clicking
        WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));
        var intPageLink = wait.Until(d => d.FindElement(By.XPath("//*[@href='/" + CountryTag + "/']")));
        intPageLink.Click();

        // Wait for the new page's footer to be fully loaded
        wait.Until(d => d.FindElement(By.ClassName("c-footer")).Displayed);
    }
    public void ScrollToFooter() {
        var actions = Browser.GetActions();
        footer = webDriver.FindElement(By.ClassName("c-footer"));
        
        if (webDriver is FirefoxDriver) {
            int i = 0;
            while (i < 5) {
                actions.SendKeys(Keys.ArrowDown).Perform();
                // Add a small delay to let scroll complete (prevents overloading the browser)
                Thread.Sleep(200);
                i++;
            }
        }
        actions.MoveToElement(footer).Perform();
    }
}

Update the Webpage class to pass only the driver to the Footer constructor:

public static class Webpage {
    public static Footer Footer {
        get {
            return new Footer(Browser.webDriver);
        }
    }
}

2. Add Explicit Waits for Page Loads

After clicking the country link, wait for the new page’s footer to be visible before scrolling. This ensures your code doesn’t run before the DOM is fully ready—a common trigger for stale element errors.

3. Alternative Scroll Method for Firefox (Optional)

Instead of relying on SendKeys, use JavaScript to scroll directly to the footer. This is more reliable across browsers and avoids state-related issues with the Actions class:

public void ScrollToFooter() {
    footer = webDriver.FindElement(By.ClassName("c-footer"));
    IJavaScriptExecutor js = (IJavaScriptExecutor)webDriver;
    js.ExecuteScript("arguments[0].scrollIntoView({behavior: 'smooth', block: 'end'});", footer);
}

Key Takeaway

Stale element errors almost always stem from trying to interact with elements from a previous DOM state. By creating fresh Actions instances for each page and adding explicit waits, you’ll ensure your code works with the current, valid DOM.

内容的提问来源于stack exchange,提问作者Morten Hovdan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:29:12