ruby—如何将nokogiri数据存储在空数组中,以便以后调用

ubbxdtey  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(222)

我正在创建一个ruby cli应用程序,它使用nokogiri从网页中刮取li元素。现在,我的应用程序将它们作为李的块返回。如何将它们分开,存储在一个数组中,以便在用户输入数字时调用?在我的cli.rb中,

def more
    input_prompt = "Enter a number between 1-42 for a random plant fact, or type 'exit' to leave:"
    puts input_prompt
    input = nil
    while input != "exit"
      input = gets.strip.to_i
        return facts
     if input == "exit"
        puts exit
      else
        puts "Sorry, I didn't understand that. #{input_prompt}" 
      end
    end
end

在我的刮刀里我有

doc = Nokogiri::HTML(open("https://www.funfactsabout.net/plant-facts/"))
doc.css("ul.facts-list li").text
end
sgtfey8w

sgtfey8w1#

def fact(number)
  doc = Nokogiri::HTML(URI.open("https://www.funfactsabout.net/plant-facts/"))
  node_set = doc.css("ul.facts-list")
  array_of_facts = node_set.children.map(&:text) - ["\n"]

  if number > array_of_facts.size
    puts "No fact under number #{number}"
  else
    puts array_of_facts[number-1]  # array indexing begins with 0
  end
end

相关问题