我如何在Ruby中捕获此异常?

时间:2011-08-01 15:57:56

标签: ruby exception-handling selenium-webdriver net-http rb-appscript

我是红宝石初学者,所以忍受我。

我正在使用selenium-webdriver和rb-appscript gems来做一些webscraping。导航到网站似乎是由Net :: Http对象驱动的,它有一个rbuf_fill方法。

运行以下代码:

sites = File.open("sites.txt", "r") if File::exists?( "sites.txt" )

    if sites != nil
       while (line = sites.gets)

              driver.switch_to.default_content

          begin
                 driver.navigate.to line

          rescue Exception
                 line = line.split.join("\n")
                 puts line + " caused a timeout."
          end

       end

...

产生此错误:

/opt/local/lib/ruby1.9/1.9.1/net/protocol.rb:140:in `rescue in rbuf_fill': Timeout::Error (Timeout::Error)
from /opt/local/lib/ruby1.9/1.9.1/net/protocol.rb:134:in `rbuf_fill'
from /opt/local/lib/ruby1.9/1.9.1/net/protocol.rb:116:in `readuntil'
from /opt/local/lib/ruby1.9/1.9.1/net/protocol.rb:126:in `readline'
from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:2219:in `read_status_line'
from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:2208:in `read_new'
from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:1191:in `transport_request'
from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:1177:in `request'
from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:1170:in `block in request'
from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:627:in `start'
from /opt/local/lib/ruby1.9/1.9.1/net/http.rb:1168:in `request'
from /opt/local/lib/ruby1.9/gems/1.9.1/gems/selenium-webdriver-2.2.0/lib/selenium/webdriver/remote/http/default.rb:73:in `response_for'
from /opt/local/lib/ruby1.9/gems/1.9.1/gems/selenium-webdriver-2.2.0/lib/selenium/webdriver/remote/http/default.rb:41:in `request'
from /opt/local/lib/ruby1.9/gems/1.9.1/gems/selenium-webdriver-2.2.0/lib/selenium/webdriver/remote/http/common.rb:34:in `call'
from /opt/local/lib/ruby1.9/gems/1.9.1/gems/selenium-webdriver-2.2.0/lib/selenium/webdriver/remote/bridge.rb:406:in `raw_execute'
from /opt/local/lib/ruby1.9/gems/1.9.1/gems/selenium-webdriver-2.2.0/lib/selenium/webdriver/remote/bridge.rb:384:in `execute'
from /opt/local/lib/ruby1.9/gems/1.9.1/gems/selenium-webdriver-2.2.0/lib/selenium/webdriver/remote/bridge.rb:171:in `switchToDefaultContent'
from /opt/local/lib/ruby1.9/gems/1.9.1/gems/selenium-webdriver-2.2.0/lib/selenium/webdriver/common/target_locator.rb:68:in `default_content'
from auto.rb:25:in `<main>'

我不知道为什么我不能抓住这个例外。使用rescue Exception 应该捕获所有内容,但正如您所看到的,我的脚本仍会崩溃。

我也发现有消息称你必须明确地捕捉超时,所以我也尝试过:

rescue Timeout::Error

没有任何运气。

非常感谢任何帮助。

Ruby版本:ruby 1.9.2p290(2011-07-09修订版32553)

操作系统:MacOS Snow Leopard 10.6.8 64位

Selenium Webdriver版本:2.2.0

1 个答案:

答案 0 :(得分:2)

Ruby标准库中的文件'timeout.rb'定义:

module Timeout
  # Raised by Timeout#timeout when the block times out.
  class Error < RuntimeError

所以rescue所需要的不是Timeout::Exception而是Timeout::Error或更一般RuntimeError。然后它应该工作。