2014-12-06 101 views
0

我有一个页面,如果它加载太慢,我想提出错误。 有一些方法的Watir类似于的Watir-webdriver的的:如何在Watir中设置默认的页面载入超时?

client = Selenium::WebDriver::Remote::Http::Default.new 
client.timeout = 10 
@browser = Watir::Browser.new :firefox, http_client: client 

回答

1

的Watir,经典不具有控制多长时间等待网页加载的API。

单击链接或使用goto方法时,将调用Browser#wait方法。这将阻止执行,直到页面被加载。这是硬编码超时,如果页面无法在5分钟内加载:

def wait(no_sleep=false) 
    @xml_parser_doc = nil 
    @down_load_time = 0.0 
    interval = 0.05 
    start_load_time = ::Time.now 

    Timeout::timeout(5*60) do 
    ... 
end 

解决方案1 ​​ - 使用超时

如果你只需要改变超时少数的场景中,最简单的选择可能是使用超时库。

例如,www.cnn.com需要9秒才能加载我的电脑。然而,只有等待5秒,你可以在一个额外的超时包裹goto(或click)方法:

Timeout::timeout(5) do 
    browser.goto 'www.cnn.com' 
end 
#=> execution expired (Timeout::Error) 

解决方案2 - 猴补丁浏览器#等待

如果你想更改为适用于所有页面,则可以覆盖Browser#wait方法以使用不同的超时。例如,覆盖它只有5秒钟:

require 'watir-classic' 

module Watir 
    class Browser 
    def wait(no_sleep=false) 
     @xml_parser_doc = nil 
     @down_load_time = 0.0 
     interval = 0.05 
     start_load_time = ::Time.now 

     # The timeout can be changed here (it is in seconds) 
     Timeout::timeout(5) do 
     begin 
      while @ie.busy 
      sleep interval 
      end 

      until READYSTATES.has_value?(@ie.readyState) 
      sleep interval 
      end 

      until @ie.document 
      sleep interval 
      end 

      documents_to_wait_for = [@ie.document] 
     rescue WIN32OLERuntimeError # IE window must have been closed 
      @down_load_time = ::Time.now - start_load_time 
      return @down_load_time 
     end 

     while doc = documents_to_wait_for.shift 
      begin 
      until READYSTATES.has_key?(doc.readyState.to_sym) 
       sleep interval 
      end 
      @url_list << doc.location.href unless @url_list.include?(doc.location.href) 
      doc.frames.length.times do |n| 
       begin 
       documents_to_wait_for << doc.frames[n.to_s].document 
       rescue WIN32OLERuntimeError, NoMethodError 
       end 
      end 
      rescue WIN32OLERuntimeError 
      end 
     end 
     end 

     @down_load_time = ::Time.now - start_load_time 
     run_error_checks 
     sleep @pause_after_wait unless no_sleep 
     @down_load_time 
    end 
    end 
end 

browser.goto 'www.cnn.com' 
#=> execution expired (Timeout::Error) 

您可以将超时值放入一个变量,以便它可以动态更改。