0

I am doing some c# selenium project, and I am continously getting StaleElementReferenceException error.

using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;

class Hello
{
    static void Main()
    {
        IWebDriver driver = new ChromeDriver();
        driver.Navigate().GoToUrl("https://www.youtube.com/");
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(1);
        if (driver.FindElement(By.XPath("//*[@id=\"content\"]/div[2]/div[6]/div[1]/ytd-button-renderer[2]/yt-button-shape/button/yt-touch-feedback-shape/div")).Displayed)
        {
            driver.FindElement(By.XPath("//*[@id=\"content\"]/div[2]/div[6]/div[1]/ytd-button-renderer[2]/yt-button-shape/button/yt-touch-feedback-shape/div")).Click();
        }
        else if (driver.FindElement(By.Id("dialog")).Displayed)
        {
            driver.FindElement(By.Id("button")).Click();
        }
        driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(12);
        driver.FindElement(By.XPath("//*[@id=\"text\"]")).Click();
    }
}

I am searching for 2 hours, I watched so many Indian tutorials. Does someone know how to fix it? error happens in this line:

driver.FindElement(By.XPath("//*[@id=\"text\"]")).Click();

Thanks.

  • Fixed! Well, for me... I was trying to click buttons on youtube (the categories), but i found out when i click on them another link opens. If someone still knows the answer it would be nice to answer for other people who have different projects than me. – Tonza-S Feb 07 '23 at 18:52
  • ditch the implicit wait(s) and use explicit wait with expected condition of element to be clickable and that should solve it. (though it won't prevent stale element exceptions from being thrown... you'd need to catch that to deal with it proper if it still occurred) Btw, if using implicit wait you only need to set it once, but you should use explicit instead... never mix implicit and explicit waits. – pcalkins Feb 07 '23 at 19:13

1 Answers1

2

Prior to the last click, within if() and else if() you are invoking click() method which may trigger a change in the DOM Tree, which possibly causing StaleElementReferenceException.


Solution

Ideally to Click() on any clickable element you have to induce WebDriverWait for the ElementToBeClickable() and you can use either of the following Locator Strategies:

  • Using CssSelector:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("#text"))).Click();
    
  • Using XPath:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//*[@id='text']"))).Click();
    
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352