9

我正在尝试单击 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

4

1 回答 1

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
于 2012-08-03T01:28:53.983 回答