2016-08-05 1 views
3

Nokogiri를 사용하여 HTML 문서에서 모든 노드를 가져 오려고합니다. 예 HTML 입력 문자열 :Nokogiri 모든 HTML 노드 가져 오기

<html> 
    <body> 
    <h1>Test</h1> 
    <p>test <strong> Jojo </strong></p> 
    </body> 
</html> 

예상 출력 :

['<html>','<body>','<h1>','</h1>','<p>','<strong>','</strong>','</p>','</body>','</html>'] 

닫기 태그와 올바른 순서가 중요합니다!

require 'nokogiri' 
string_page = "<html><body><h1>Header1</h1></body></html>" 
doc = Nokogiri::HTML(string_page) 
doc.search('*').map(&:name) 
# => ["html", "body", "h1"] 

을하지만 닫는 태그를 반환하지 않습니다

는 이미이 코드를 시도했다.

답변

4

자체 닫기가 아닌 모든 시작 요소의 InnerXml을 통해 OuterXml을 나눌 수 있으며, 해당 닫는 요소가 있으면이를 검색하여 검색하고 Nokogiri 판독기를 사용하여 문서를 구문 분석하여 문서 내의 순서에 따라 목록을 작성할 수 있습니다 .

문서가 XML 파서를 사용하는 것과 HTML 파서를 사용하지 않는 유효한 XML 조각이어야합니다.

require 'nokogiri' 
[ "<html><body><h1>Header1</h1></body></html>", 
"<html><body><div><h1>Title</h1><hr /></div><div><p>Lorem Ipsum<br />sit <span class=\"style\">d</span>olor</p></div></body></html>", <<END 
<html> 
    <body> 
     <h1>Test</h1> 
     <p>test <strong> Jojo </strong></p> 
    </body> 
</html> 
END 
].each { |string_page| 
    elem_all = Array.new 
    elem_ends = Hash.new 
    reader = Nokogiri::XML::Reader(string_page) 
    reader.each { |node| 
    if node.node_type.eql?(1) 
     if node.self_closing? 
     elem_all << node.outer_xml 
     else 
     elem_tags = node.outer_xml.split(node.inner_xml) 
     elem_all << elem_tags.first 
     elem_ends[node.local_name] = elem_tags[1] unless elem_tags.one? 
     end 
    end 
    elem_all << elem_ends[node.local_name] if node.node_type.eql?(15) and elem_ends.has_key?(node.local_name) 
    } 

    puts string_page 
    puts elem_all.to_s 
    puts 
} 

출력 :

doc = Nokogiri::HTML(<<EOT) 
<html> 
    <body> 
    <h1>Test</h1> 
    <p>test <strong> Jojo </strong></p> 
    </body> 
</html> 
EOT 

doc.search('*').map{|m| [m.name, "/#{m.name}"]} 

출력 :

<html><body><h1>Header1</h1></body></html> 
["<html>", "<body>", "<h1>", "</h1>", "</body>", "</html>"] 

<html><body><div><h1>Title</h1><hr /></div><div><p>Lorem Ipsum<br />sit <span class="style">d</span>olor</p></div></body></html> 
["<html>", "<body>", "<div>", "<h1>", "</h1>", "<hr/>", "</div>", "<div>", "<p>", "<br/>", "<span class=\"style\">", "</span>", "</p>", "</div>", "</body>", "</html>"] 

<html> 
    <body> 
     <h1>Test</h1> 
     <p>test <strong> Jojo </strong></p> 
    </body> 
</html> 
["<html>", "<body>", "<h1>", "</h1>", "<p>", "<strong>", "</strong>", "</p>", "</body>", "</html>"] 
0

당신은 아래와 같이 자신의 닫는 태그 설정할 수 있습니다 => [[ "HTML", "/ html로"를, [ "body", "/ body"], [ "h1", "/ h1"], [ "p", "/ strong"]

+0

"올바른 순서가 중요합니다! " –