변수 parent_element_h1
및 parent_element_h2
을 채우려고합니다. 누구든지 그 변수에 필요한 정보를 얻기 위해 Nokogiri을 사용할 수 있습니까?Nokogiri를 사용하여 DOM을 탐색하는 방법
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
의 형제가 될 수 있습니다.
다음 재귀 방법은 좋은 출발점이지만 start_here
의 형제의 자식이기 때문에이 <h1>
에서 작동하지 않습니다 :
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')
이 답변에 동의 한 후, 내가 와서 my own solution. 그것은 매력처럼 작동하고 나는 그것이 꽤 멋지다라고 생각한다.
문제는 헤더가 형제 또는 형제 자매인지 여부입니다. 당신의 솔루션은 내가 형제인지 형제인지를 알고 있다고 가정합니다. 그 외에도 예제 데이터는 실제 데이터보다 훨씬 짧습니다. 'my_tag'는 문서 내부의 어느 위치 에나있을 수 있습니다. – Javier
형제/자식 관계가 확실하지 않은 경우 XPath에서 '/ html/body /'또는 '/ html/body // div'대신 '//'을 사용할 수 있습니다. http://www.w3schools.com/Xpath/ –
제 생각에는 제 질문이 구체적이지 않다고 생각합니다. 질문을 편집했고 지금 내가 원하는 것을 분명히하기를 바랍니다. (변수 위에있는 주석을 확인하십시오. 데이터로 채우기 위해 노력하고 있음). – Javier