Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 214
Иван Бишевац Avatar asked Aug 03 '12 00:08

Иван Бишевац


1 Answers

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
like image 101
Justin Ko Avatar answered Sep 30 '22 02:09

Justin Ko