Element not found in the cache - perhaps the page has changed since it was looked up (Selenium::WebDriver::Error::StaleElementReferenceError)

Иван Бишевац picture Иван Бишевац · Aug 3, 2012 · Viewed 8.9k times · Source

I am trying to click all links on stackoveflow horizontal menu (Questions, Tags, Users, Badges, Unanswered). I have this code but this clicks on first link (this link is Questions), then prints 1, and after that raises error. What could be problem with this?

require 'watir-webdriver'

class Stackoverflow
  def click_all_nav_links
    b = Watir::Browser.new
    b.goto "http://stackoverflow.com"

    counter = 0
    b.div(:id => 'hmenus').div(:class => 'nav mainnavs').ul.lis.each do |li|
      li.a.click
      puts counter += 1
    end
  end
end

stackoverflow = Stackoverflow.new
stackoverflow.click_all_nav_links

Error message is: https://gist.github.com/3242300

Answer

Justin Ko picture Justin Ko · Aug 3, 2012

The StaleElementReferenceError often occurs when storing elements and then trying to access them after going to another page. In this case, the reference to the lis becomes stale after you click the links and navigate to a new page.

You have to store off attributes or the index of the lis first. This will allow you to get a fresh reference to each li after clicking a link.

Try this:

class Stackoverflow
    def click_all_nav_links
        b = Watir::Browser.new
        b.goto "http://stackoverflow.com"

        #Store the text of each locate so that it can be located later
        tabs = b.div(:id => 'hmenus').div(:class => 'nav mainnavs').ul.lis.collect{ |x| x.text }

        #Iterate through the tabs, using a fresh reference each time
        tabs.each do |x|
            b.div(:id => 'hmenus').div(:class => 'nav mainnavs').ul.li(:text, x).a.click
        end
    end
end

stackoverflow = Stackoverflow.new
stackoverflow.click_all_nav_links