【发布时间】:2017-03-28 16:03:23
【问题描述】:
我经常发现自己要处理这些情况:
require 'nokogiri'
require "open-uri"
url = "https://www.random_website.com/contains_info_I_want_to_parse"
nokodoc = Nokogiri::HTML(open(url))
# Let's say one of the following line breaks the ruby script
# because the element I'm searching doesn't contain an attribute.
a = nokodoc.search('#element-1').attribute('href').text
b = nokodoc.search('#element-2').attribute('href').text.gsub("a", "A")
c = nokodoc.search('#element-3 h1').attribute('style').text.strip
我将创建大约 30 个变量来搜索页面中的不同元素,并且我将在多个页面上循环该代码。但是,其中一些页面的布局可能略有不同,并且不会有其中一个 div。这将破坏我的代码(例如,因为您不能在 nil 上调用 .attribute 或 .gsub )。但我永远无法事先猜到哪一行。 我的首选解决方案通常是在每一行周围加上:
begin
line #n
rescue
puts "line #n caused an error"
end
我希望能够做类似的事情:
url = "https://www.random_website.com/contains_info_I_want_to_parse"
nokodoc = Nokogiri::HTML(open(url))
catch_error(a, nokodoc.search('#element-1').attribute('href').text)
catch_error(b, nokodoc.search('#element-2').attribute('href').text.gsub("a", "A"))
catch_error(c, nokodoc.search('#element-3 h1').attribute('style').text.strip)
def catch_error(variable_name, code)
begin
variable_name = code
rescue
puts "Code in #{variable_name} caused an error"
end
variable_name
end
我知道在每个新方法之前加上 & 是有效的:
nokodoc.search('#element-1')&.attribute('href')&.text
但我希望能够在我的终端中使用“puts”来显示错误,以查看我的代码何时出现错误。
有可能吗?
【问题讨论】:
标签: ruby methods error-handling nokogiri rescue