【问题标题】:ruby webdriver ERROR: Element not found in the cache - perhaps the page has changed since it was looked upruby webdriver 错误:在缓存中找不到元素 - 页面可能在查找后已更改
【发布时间】:2013-07-10 05:40:23
【问题描述】:

我要查找页面上的所有 li 元素,它们在它们的属性中都有唯一的 id,其中一些是隐藏的,单击页面上的更多按钮可以使它们可见。这是代码:

def open_template id=0
      sleep 1
      #try to get all the li elements that has class named like "test..." and put them into a list
      box_list=browser.lis.find_all { |div| div.class_name =~ /^test/ }   
      sleep 2
      #go though the list
      box_list.each do |each|
         str=each.a.attribute_value("href")
         #the tid number of the element should match to id
         if /\?tid=\d+/.match(str)[0].gsub!("?tid=", "").to_i==id
            # if the element is hidden, should click the "more" button and get into another page
            if each.attribute_value("style")=="display: none;"
              each.parent.parent.div(class: "title_me_h").a(class: "more").click
              sleep 2
              # begin the same thing on the new page
              open_template(id)
            end
            begin
              #if the element matchs and isn't hidden, do a click          
              each.a(class: "li_box_cj").wait_until_present 
              each.a(class: "li_box_cj").click
            rescue Exception => e
              puts "ERROR: #{e.message}"            
            end
            break
         end
      end
    end

当我试图找到一个隐藏的 li 元素时,执行代码后我得到元素在缓存中找不到错误,但最后一个动作“点击”被执行了。我不明白为什么,谁能给我一些建议?我已阅读有关 stackoverflow 的所有相关问题,但没有得到答案。提前谢谢。

【问题讨论】:

  • 点击后,DOM 发生变化(使 li 可见),但您尝试循环的列表在点击之前生成,因此抛出异常。
  • 感谢您的热心回答,我的代码中存在逻辑错误,需要一个“else”来跳出循环,非常感谢

标签: ruby caching webdriver


【解决方案1】:
def open_template id=0
  sleep 1
  box_list=browser.lis.find_all { |div| div.class_name =~ /^test/ }   
  sleep 2
  box_list.each do |each|
     str=each.a.attribute_value("href")
     if /\?tid=\d+/.match(str)[0].gsub!("?tid=", "").to_i==id
        if each.attribute_value("style")=="display: none;"
          each.parent.parent.div(class: "title_me_h").a(class: "more").click
          sleep 2
          open_template(id)
        #add else here to break out of the loop
        else
        begin
          #if the element matchs and isn't hidden, do a click          
          each.a(class: "li_box_cj").wait_until_present 
          each.a(class: "li_box_cj").click
        rescue Exception => e
          puts "ERROR: #{e.message}"            
        end
        end
        break
     end
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多