我正在使用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/","https://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 https://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 https://stackoverflow.com/
看起来浏览器在完成加载页面之前不响应任何其他命令.如何强制浏览器丢弃正在加载的页面并执行下一个命令?
更新
我找到了一个有趣的功能标志loadAsync http://src.chromium.org/svn/trunk/src/chrome/test/webdriver/webdriver_capabilities_parser.cc也许它对解决这个问题有用吗?我还不明白如何在启动chromedriver时让watir(webdriver)设置它.这个标志在这里介绍了http://codereview.chromium.org/7582005/
解决方法
有几种不同的方法可以做你想要的,但这就是我要做的事情:
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
如果您有很多站点正在尝试加载以确认超时,请将它们放在一个数组中:
mySites = [ mySite1,mySite2,mySite3 ] mySites.each do |site| begin @browser.goto site rescue "Puts #{site} Failed to load within the time allotted." end end
更新概念证明.该脚本总是进行到第2步.第二个goto甚至不需要救援,但是用于更清晰的输出.你的剧本与此有何不同?
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