Ruby 切换,只显示第一个和最后一个

Ruby switch, show only first and last

我正在使用 nokogiri 抓取网页:

doc = Nokogiri::HTML(File.read(html))    
doc.each do |node|
  case node.name
  when 'h1'
    Puts node.text
  when 'h2'
    puts node.text
  when 'h3'
    puts node.text
  when 'h4'
    puts node.text
  when 'h5'
    puts node.text
  end
end

有很多h5。我不想将它们全部列出,而是将它们组合在一起并仅在各自的 h4 下方显示第一个和最后一个。

您可以定义一个标志来检测它是否是第一个 h5 条目。 如果是第一个,则打印文本。然后将文本存储在一个变量中以备后用。

如果关卡从 h5 重置,您必须写下最后一个节点文本。

最后还要写最后一个节点文本

像这样:

doc = Nokogiri::HTML(File.read(html))    
first_flag = true
last_h5 = nil
doc.each do |node|
  #there was a h5 and now we have new version
  if first_flag == false and  node.name != 'h5'
    puts last_h5    
    first_flag = true
  end
  case node.name
  when 'h1'
    puts node.text
  when 'h2'
    puts node.text
  when 'h3'
    puts node.text
  when 'h4'
    puts node.text
  when 'h5'
    puts node.text if first_flag 
    first_flag = false
    last_h5 = node.text 
  end    
end

  #Write the last entry
  if first_flag == false and last_h5
    puts last_h5 
  end

如果只有一个,此代码将重复 h5 文本。但是根据你的描述,你的数据不是这样的。

免责声明:未经测试的代码,缺少测试 html ;)


如果用计数器替换布尔标志,那么您也可以用一个 h5 节点捕获边缘情况。

示例:

h5_count = 0
last_h5 = nil
doc.each do |node|
  #there was a h5 and now we have new version
  if h5_count > 1 and  node.name != 'h5'
    puts last_h5    
    h5_count = 0
  end
  case node.name
  when 'h1'
    puts node.text
  when 'h2'
    puts node.text
  when 'h3'
    puts node.text
  when 'h4'
    puts node.text
  when 'h5'
    puts node.text if h5_count == 0
    h5_count += 1
    last_h5 = node.text 
  end    
end

  #Write the last entry
  if h5_count > 1
    puts last_h5    
  end