在缓存中找不到元素 - 自查询以来页面可能已更改(Selenium :: WebDriver :: Error :: StaleElementReferenceError)

时间:2012-08-03 00:04:39

标签: ruby watir-webdriver

我试图点击stackoveflow水平菜单上的所有链接(问题,标签,用户,徽章,未答复)。我有这个代码但是点击第一个链接(这个链接是问题),然后打印1,然后引发错误。这可能有什么问题?

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

错误讯息是: https://gist.github.com/3242300

1 个答案:

答案 0 :(得分:15)

StaleElementReferenceError经常在存储元素时发生,然后在转到另一个页面后尝试访问它们。在这种情况下,单击链接并导航到新页面后,对lis的引用将变为陈旧。

您必须首先存储属性或lis的索引。这样,您可以在点击链接后获得每个li的新参考。

试试这个:

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