parent_element_h1
変数とを埋めようとしていますparent_element_h2
。Nokogiriを使用して必要な情報をこれらの変数に取得するのを手伝ってくれる人はいますか?
require 'rubygems'
require 'nokogiri'
value = Nokogiri::HTML.parse(<<-HTML_END)
"<html>
<body>
<p id='para-1'>A</p>
<div class='block' id='X1'>
<h1>Foo</h1>
<p id='para-2'>B</p>
</div>
<p id='para-3'>C</p>
<h2>Bar</h2>
<p id='para-4'>D</p>
<p id='para-5'>E</p>
<div class='block' id='X2'>
<p id='para-6'>F</p>
</div>
</body>
</html>"
HTML_END
parent = value.css('body').first
# start_here is given: A Nokogiri::XML::Element of the <div> with the id 'X2
start_here = parent.at('div.block#X2')
# this should be a Nokogiri::XML::Element of the nearest, previous h1.
# in this example it's the one with the value 'Foo'
parent_element_h1 =
# this should be a Nokogiri::XML::Element of the nearest, previous h2.
# in this example it's the one with the value 'Bar'
parent_element_h2 =
注意:start_here
要素はドキュメント内のどこにでもある可能性があります。HTML データは単なる例です。つまり、ヘッダー<h1>
およびは、 の兄弟または の兄弟の子である<h2>
可能性があります。start_here
start_here
<h1>
次の再帰的メソッドは出発点としては適切ですが、 の兄弟の子であるため機能しませんstart_here
。
def search_element(_block,_style)
unless _block.nil?
if _block.name == _style
return _block
else
search_element(_block.previous,_style)
end
else
return false
end
end
parent_element_h1 = search_element(start_here,'h1')
parent_element_h2 = search_element(start_here,'h2')
答えを受け入れた後、私は自分の解決策を思いつきました。それは魔法のように機能し、かなりクールだと思います。