【问题标题】:How do I get my rails app to work around errors?如何让我的 rails 应用程序解决错误?
【发布时间】:2013-11-26 18:43:43
【问题描述】:

我的 rails 应用是一个使用 Mechanize / Nokogiri 的网络爬虫。由于 KBB.com 及其 cookie 的问题,每次我向他们的服务器发出新的获取请求时,我都必须清除我的应用程序中的 cookie jar。

agent.cookie_jar.clear!

但是,当我的应用正在抓取数据时,它偶尔会遇到带有自动重定向的 KBB.cpm 页面!这会导致错误:

Mechanize::ResponseCodeError: 500 => Net::HTTPInternalServerError for http://www.kbb.com/toyota/prius/2002-toyota-prius/sedan-4d/options/?vehicleid=4843&intent=buy-used -- unhandled response

这会导致我的 rails 应用程序崩溃,因为在重定向之前我无法清除 cookie jar。相反,我想让我的应用程序做的是认识到它可能会遇到错误,并且如果它确实使用不同的进程。比如:

if there_is_an_error
  # alternative process for redirect
else
  # business as usual
end

这是我的代码:

agent = Mechanize.new
agent.cookie_jar.clear!
page = agent.get(url)
agent.cookie_jar.clear!
page.link_with(:text => "Choose this style").click
agent.cookie_jar.clear!
agent.page.link_with(:text => "Choose price type").click
agent.cookie_jar.clear!
agent.page.links_with(:text => "Get used car price")[2].click
url = agent.page.uri.to_s.sub('retail', 'private-party')
agent.cookie_jar.clear!
agent.get(url)
@kbb_value = agent.page.at('.selected .value').text.delete('$')

【问题讨论】:

    标签: ruby-on-rails error-handling mechanize


    【解决方案1】:

    您应该查看http://www.tutorialspoint.com/ruby/ruby_exceptions.htm 处理异常。还有一个关于此的堆栈溢出帖子:Begin, Rescue and Ensure in Ruby?。您可以通过在异常处理块中设置一个标志来解决您的问题,然后稍后在您的代码中检查该标志以确定是否发生了异常,这应该可以解决您的问题。

    【讨论】:

      【解决方案2】:

      您可以挽救 Mechanize::ResponseCodeError 异常并在该块内执行替代过程以进行重定向

      【讨论】:

        猜你喜欢
        • 2011-06-08
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多