Search code examples
rubyseleniumstaleobjectstateexception

StaleElementReferenceError in ruby selenium


I was trying to automate rediff.com . I went from one page to other but when i came back i got staleException . I tried a lot but couldn't fix it. I am attaching the code snippet too. Any help would be appreciated.

@driver.get "http://shopping.rediff.com/?sc_cid=inhome_icon"

@driver.manage.window.maximize

wait = Selenium::WebDriver::Wait.new(:timeout => 10) # seconds

begin

element = wait.until { @driver.find_element(:xpath,".//*[@id='popular_cat']") }

ensure

[email protected]_element(:xpath,".//*[@id='popular_cat']")

end links=box.find_elements(:tag_name,"a")

puts "Total links are:#{links.size}"

links.each do |i|

  puts "--------------------"
  puts "Value of all links is:#{i.text}"
  i.click
  puts "Title of page is :#{@driver.title}"
  @driver.get "http://shopping.rediff.com/?sc_cid=inhome_icon"
  [email protected]_element(:xpath,".//*[@id='popular_cat']")
  links=box.find_elements(:tag_name,"a")

end

Solution

  • Every time you reload the page (because you are going to other page and then going back or because you simple reloaded the page) your references to the links 'links=box.find_elements(:tag_name,"a")' are lost.

    I would suggest a few changes in order to workaround this (might not be the best solution)

    links = box.find_elements(:tag_name,"a").size links_counter = 0 while links_counter < links box = @driver.find_element(:xpath,".//*[@id='popular_cat']") current_link = box.find_elements(:tag_name,"a")[links_counter] links_counter += 1 puts "--------------------" puts "Value of all links is:#{current_link.text}" current_link.click puts "Title of page is :#{@driver.title}" @driver.get "http://shopping.rediff.com/?sc_cid=inhome_icon" end

    I hope this helps you!

    Best, Fernando