0
IWebElement table = driver.FindElement(By.ClassName("mozaique"));
IList<IWebElement> list = table.FindElements(By.ClassName("thumb-block "));

foreach (var item in list)
{
    item.Click();
    driver.FindElement(By.CssSelector("span.icon.download")).Click();
    waitforDWNlink();
    driver.Navigate().Back();
    driver.Navigate().GoToUrl(URL);
}

The first time when I'm going through the foreach loop it works fine. Inside the foreach loop I navigate to another page. After that, when iterating again in the foreach loop, it gives me an exception.

What am I doing wrong?

EDIT: After seeing one of the answers I tried this:

IWebElement table = driver.FindElement(By.ClassName("mozaique"));
IList<IWebElement> list = table.FindElements(By.ClassName("thumb-block "));

List<string> NewList= new List<string>();
            foreach (var item in list)
            {
                NewList.Add(item.GetAttribute("href"));
            }

I was trying to store the href on a new list item.But after running the code ,the new list item was blank.

1
  • What kind of exception? A Stale Element Exception?
    – kirbycope
    Commented May 30, 2017 at 15:41

2 Answers 2

5

You are likely getting a StaleElementException. When you first get the list of elements to click, they are attached to the current DOM. After navigating away (the first time) the elements are no longer attached to the DOM (even if you navigate back). One way of getting around this is to:

  1. Get all the HREFs of the elements and store that into a list
  2. Visit each HREF and do your actions/verifications
0

Don't do this:

 foreach (var item in list)

This implies you already have a list of references to existing elements, as soon as you navigate those elements are toast.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.