0

I get the number of pages from an element that the table can display. I then create a loop that will click the next button until the current page element reads the last page.

The problem each time I click the next button selenium is unable realise that I am referring to the new elements that have been loaded. I have tried everything.

string NumberOfPages = driver.FindElement(By.XPath("//*[@id=\"maxCA\"]")).Text;
for (int i=0; i< Int32.Parse(NumberOfPages); i++)
{
    driver.FindElement(By.XPath("//*[@id=\"BID_WINDOW_CONTAINER\"]/div[4]/div[3]/span[3]")).Click();
    WebDriverWait wait2 = new WebDriverWait(driver, System.TimeSpan.FromSeconds(3));
    var ready2 = wait.Until(ExpectedConditions.ElementExists(By.CssSelector(".AUCTION_ITEM")));
    Head_W = driver.FindElement(By.CssSelector(".Head_C"));
    ScrapeProperties(Head_W);
}

I know what is going on. I am just not sure how to make Selenium realise that I am referring to the new element that has been created rather than the previous element. You can see in my loop I start from the root document so I presume this will capture the new elements instead. The error happens in ScrapeProperties(Head_W); when I do something like;

IList<IWebElement> AuctionItems = Head_W.FindElements(By.CssSelector(".AUCTION_ITEM")).ToList();
//In a loop I do this;
property.AuctionStatus = AuctionItemElement.FindElement(By.CssSelector("div.AUCTION_STATS > div.ASTAT_MSGB.Astat_DATA")).Text;
  • 1
    Possible duplicate of [StaleElementReference Exception in PageFactory](https://stackoverflow.com/questions/44838538/staleelementreference-exception-in-pagefactory) – undetected Selenium Nov 21 '17 at 03:32
  • If the page changes after clicking the next button, try to find something on the page that becomes different then what it was before, and create a custom wait to make sure that element actually is different than what it was before, while making sure you catch any stale element exceptions during the wait. – mrfreester Nov 21 '17 at 17:57

1 Answers1

0

Element is not attached to the page seems like a stale element exception. I recommend to use a generic wrapper method over findElement call and add specific catch blocks to handle such exceptional situation. Refer to the code snippet below.

public WebElement findFreshElement(By locator){ 
      WebElement webElement = null;
      int attempts =0;
      while(attempts < 10){
      try {
          wait.hardWait(1);
          webElement = driver.findElement(locator);
          webElement.isDisplayed();
          break;
      } catch (StaleElementReferenceException e) {
          logMessage("⚠ Stale Element Reference Exception ... Refinding element after a second.. ");
          attempts+=1;
      }catch(NoSuchElementException e){
           logMessage("[ELEMENT NOT FOUND] : You might have to update the locator:-" + locator);
        attempts+=1;     
        }
      }
      return webElement;

    }
Manmohan_singh
  • 1,776
  • 3
  • 20
  • 29