我正在尝试从Nokogiri NodeSet中获取随机元素。
我尝试过
nodeset.sample(10)
where
nodeset = html_page.css('div')
但是这会导致错误:
undefined method `sample' for #<Nokogiri::XML::NodeSet:0x15f44c70>
阅读Nokogiri的rubydocs:
#to_a ⇒ Object (also: #to_ary)
Return this list as an Array.
它们没有任何功能可让您从NodeSet中检索随机元素,但是,它们允许您使用to_a
转换NodeSet,然后可以使用常规数组函数来获取随机记录。
nodeset.to_a.sample(10)