Getting a stale element exception (Selenium - Java)



  • I am using Selenium via Java.

    I am running into a stale element exception and I can't seem to identify the issue.

    I am interacting with a carousel (see image below). I have placed all the vehicles, in the carousel, into a list and I am trying to get the text back from each web element in the list. The list contains eight elements. When my code interacts with the last page of the carousel (in this case the sixth element in the list) a stale element exception gets thrown.

    Here is the code where I placed all the vehicles in the carousel in a list:

    List vehiclesInCarousel = driver.findElements(By.cssSelector("div[data-qaid='cntnr-frntlnlstng-carousel'] ul[class='slider-list'] li[class='slider-slide']"));
    

    enter image description here



  • Two reasons for Stale element

    1. An element that is found on a web page referenced as a WebElement in WebDriver then the DOM changes (probably due to JavaScript functions) that WebElement goes stale.

    2. The element has been deleted entirely.

    When you try to interact with the staled WebElement[any above case], the StaleElementException is thrown.

    Solutions to resolve them:

    1. Storing locators to your elements instead of references

    DON'T

     driver = webdriver.Firefox();
     driver.get("http://www.github.com");
     search_input = driver.find_element_by_name('q');
    

    search_input.send_keys('hello world\n'); // Page contents refresh after typing in search results.
    time.sleep(5);

    search_input.send_keys('hello frank\n'); // StaleElementReferenceException

    Do

    driver = webdriver.Firefox();
    driver.get("http://www.github.com");
    search_input = lambda: driver.find_element_by_name('q');
    search_input().send_keys('hello world\n'); 
    time.sleep(5);
    

    search_input().send_keys('hello frank\n') // no stale element exception

    1. Leverage hooks in the JS libraries used
       # Using Jquery queue to get animation queue length.
        animationQueueIs = """
        return $.queue( $("#%s")[0], "fx").length;
        """ % element_id
        wait_until(lambda: self.driver.execute_script(animationQueueIs)==0)
    
    1. Moving your actions into JavaScript injection
     self.driver.execute_script("$(\"li:contains('Narendra')\").click()");
    
    1. Proactively wait for the element to go stale
      # Wait till the element goes stale, this means the list has updated
      wait_until(lambda: is_element_stale(old_link_reference))
    

    This solution, which worked for me, I have mentioned here if you have any additional scenario, which worked for you then comment below or contact me so that we can add into solution list



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2