Sohel
Sohel

Reputation: 676

Selenium C# - How to Check All Links

I am trying to check all links on a page. Some questions already were asked on this topic, but for some reason none are working when I tried. One particular issue I'm having is that after going to a page and after getting all links into a list variable, when looping through them, error message shows the link to be a stale reference. Here is the code snippet:

var driver = new FirefoxDriver();
driver.Navigate().GoToUrl(URLPROD);
driver.Manage().Window.Maximize();

ICollection<IWebElement> links = driver.FindElements(By.TagName("a"));

foreach (var link in links)
{
   if (!(link.Text.Contains("Email")) || !(link.Text == "") || !(link.Text == null) || !(link.Text.Contains("Element")))
   {
      ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", link);
      Console.WriteLine(link);
      driver.ExecuteScript("arguments[0].click();", link);

      driver.Navigate().Back();

    }

}

Error message: OpenQA.Selenium.StaleElementReferenceException: 'The element reference of is stale; either the element is no longer attached to the DOM, it is not in the current frame context, or the document has been refreshed'

What should I be doing to correct this error so that I can check each link on a page?

Upvotes: 0

Views: 1679

Answers (1)

Ywapom
Ywapom

Reputation: 601

You could just re-find the links. So 1. get number of links 2. loop that number getting the links fresh each time (to avoid stale errors).

        var links = driver.FindElements(By.TagName("a"));

        for (int i=0; i < links.Count(); i++)
        {
            var newLinks = driver.FindElements(By.TagName("a"));
            newLinks[i].Click();
            driver.Navigate().Back();
        }

Upvotes: 1

Related Questions