我正在尝试填充变量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')
接受答案后,我想出了自己的解决方案。它就像一个魅力,我认为它很酷。