Tonza-S
Tonza-S

Reputation: 23

C# selenium stale element reference exception

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.

Upvotes: 1

Views: 634

Answers (1)

undetected Selenium
undetected Selenium

Reputation: 193108

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();
    

Upvotes: 4

Related Questions