使无头浏览器停止加载页面

Mol*_*far 8 ruby webdriver watir watir-webdriver selenium-chromedriver

我正在使用watir-webdriver ruby​​ gem.它启动浏览器(Chrome)并开始加载页面.页面加载太慢,watir-webdriver引发超时错误.如何让浏览器停止加载页面?

require 'watir-webdriver'

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

sites = [
  "http://google.com/",
  "http://yahoo.com/",
  "http://www.nst.com.my/", # => This is the SLOW site
  "http://drupal.org/",
  "http://www.msn.com/",
  "http://stackoverflow.com/"
]

sites.each do |url|

  begin
    @browser.goto(url)
    puts "Success #{url}"
  rescue
    puts "Timeout #{url}"
  end

end

########## Execution result ########## 

# Success http://google.com/
# Success http://yahoo.com/
# Timeout http://www.nst.com.my/
# Timeout http://drupal.org/
# Timeout http://www.msn.com/
# Timeout http://stackoverflow.com/

########## Expected result ########## 

# Success http://google.com/
# Success http://yahoo.com/
# Timeout http://www.nst.com.my/
# Success http://drupal.org/
# Success http://www.msn.com/
# Success http://stackoverflow.com/
Run Code Online (Sandbox Code Playgroud)

看起来浏览器在完成加载页面之前不响应任何其他命令.如何强制浏览器丢弃正在加载的页面并执行下一个命令?

更新

我找到了一个有趣的功能标志loadAsync http://src.chromium.org/svn/trunk/src/chrome/test/webdriver/webdriver_capabilities_parser.cc也许它对解决这个问题有用吗?我还不明白如何在启动chromedriver时让watir(webdriver)设置它.这个标志在这里介绍http://codereview.chromium.org/7582005/

ada*_*eed 4

有几种不同的方法可以实现您想要的功能,但我会这样做:

require 'watir-webdriver'

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

begin
  @browser.goto mySite
rescue => e
  puts "Browser timed out: #{e}"
end

next_command
Run Code Online (Sandbox Code Playgroud)

如果您有很多站点要尝试加载以确认是否超时,请将它们放入一个数组中:

mySites = [
          mySite1,
          mySite2,
          mySite3
]

mySites.each do |site|
   begin
      @browser.goto site
   rescue
      "Puts #{site} failed to load within the time allotted."
   end
end
Run Code Online (Sandbox Code Playgroud)

更新概念证明。该脚本始终继续执行步骤 2。第二次跳转甚至不需要救援,但可用于更清晰的输出。您的脚本与此有何不同?

require 'watir-webdriver'

client = Selenium::WebDriver::Remote::Http::Default.new
client.timeout = 1     #VERY low timeout to make most sites fail
@browser = Watir::Browser.new :firefox, :http_client => client


def testing
   begin
     @browser.goto "http://www.cnn.com"
   rescue => e
     puts "Browser timed out on the first example"
   end

   begin
     @browser.goto "http://www.foxnews.com"
   rescue => e
     puts "Browser timed out on the second example"
   end
end
Run Code Online (Sandbox Code Playgroud)