Eu estou tentando preencher as variáveis parent_element_h1
e parent_element_h2
. Alguém pode me ajudar a usar Nokogiri para obter a informação de que preciso para essas variáveis?
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 =
Atenção: O start_here
elemento pode ser qualquer lugar dentro do documento. Os dados HTML é apenas um exemplo. Dito isto, os cabeçalhos <h1>
e <h2>
poderia ser um irmão de start_here
ou um filho de um irmão de start_here
.
O método recursivo a seguir é um bom ponto de partida, mas não funciona em <h1>
porque é um filho de um irmão de 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')
Depois de aceitar uma resposta, eu vim com a minha própria solução . Ele funciona como um encanto e eu acho que é muito legal.