2

I want to drill down the tree, and store all the levels:

search_q = Regex.new("Some search regex here")
#something like: page.search('body').first.children.select {|x| x.text[search_q]}.first.children.select {|x| x.text[search_q]}.first......ad infinitum.

I've done a hack:

arbitrarily_long_number = 100
drill = []
(0..arbitrarily_long_number).collect do |n|
  begin
    drill << eval("page.search('body')"+".first.children.select {|x| x.text[search_q]}" * n)
  rescue
    break
  end
end

The problem is that this drills only through the "first" selection. Is there a way to make it drill through every node? I'm thinking of some sort of inject function, but I still haven't wrapped my head around it. Any help would be appreciated.

Output:

pp drill[-4]
puts
pp drill[-3]
puts
pp drill[-2]
#=>[#(Element:0x3fc2324522b4 {
   name = "u",
   children = [
     #(Element:0x3fc232060b60 {
       name = "span",
       attributes = [
         #(Attr:0x3fc2320603e0 {
           name = "style",
           value = "font-size: large;"
           })],
       children = [ #(Text "Ingredients:")]
       })]
   })]

[#(Element:0x3fc232060b60 {
   name = "span",
   attributes = [
     #(Attr:0x3fc2320603e0 { name = "style", value = "font-size: large;" })],
   children = [ #(Text "Ingredients:")]
   })]

[#(Text "Ingredients:")]

Notes: I'm using the mechanize gem, which leverages off of Nokogiri. http://mechanize.rubyforge.org/Mechanize/Page.html#method-i-search http://nokogiri.org/Nokogiri/XML/Node.html#method-i-search

4

2 回答 2

2

对我来说,这听起来像你想要遍历:

doc.traverse do |node|
  drill << node
end
于 2012-09-15T00:25:08.160 回答
1

你的问题不清楚。

如果,通过

我想向下钻取树,并存储所有级别:

你的意思是你想遍历所有节点,告诉 Nokogiri 这样做。

require 'nokogiri'

doc = Nokogiri::XML(<<EOT)
<a>
  <b>
    <c>1</c>
  </b>
</a>
EOT

doc.search('*').each do |n|
  puts n.name
end

将其粘贴到 IRB 并获取输出:

irb(main):011:0* doc.search('*').each do |n|
irb(main):012:1*   puts n.name
irb(main):013:1> end
a
b
c

我使用了 XML,而您使用的是 HTML,但这无关紧要。您必须更改docpage适应 Mechanize 的方式,但这很容易。

于 2012-09-14T17:38:45.697 回答