Thursday, June 1, 2017

Over come with StaleElementException at selenium

My original problem was ,
I was trying to extract some web element list from a IList  item and try to use those IList items inside a foreach loop.

Inside the foreach loop I navigate to another page. After that, when iterating again in the foreach loop, it gives me an exception.

This is how my code looks like.

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




My solution was ,
I extract the HREF / URL from the each item at the IList  and store them at a string type array.

After that i use that HREF url to navigate to the relavant web page using 
driver.Navigate().GoToUrl().

IWebElement table = driver.FindElement(By.ClassName("mozaique"));
IList<IWebElement> list = table.FindElements(By.TagName("a"));
               
       string[] URL1 = new string[list.Count];
                
       int i = 0;
       foreach (var item in list)
                {
                 URL1[i] = list[i].GetAttribute("href").ToString();
                 i++;

                }

Hard part was converting IWebElement type list to string type array which is done at the highlighted lines.

No comments:

Post a Comment