2009-12-06 2 views
1

이의 내가이 샘플 있다고 가정 해 봅시다 :노코 기리 부모 텍스트가 아닌 차일 텍스트를 얻을 부모로 다시 텍스트를 참조하는 방법을

page = "<html><body><h1 class='foo'></h1><p class='foo'>hello people<a href='http://'>hello world</a></p></body></html>" 
    @nodes = [] 
    Nokogiri::HTML(page).traverse do |n| 
     if n[:class] == "foo" 
      @nodes << {:name => n.name, :xpath => n.path, :text => n.text } 
     end 
    end 

결과가 n.texthello peoplehello world을 것 것이기를, 내가 원하는 방법으로 그것을 할 것은 그래서 부모 텍스트와 차일 텍스트를 얻을 수 있지만, 자신의 태그

에게 관련 될 수 있으므로 결과가 될이

@nodes[0][:text]="" 
@node[1][:text]= [{:Elementtext1 => "hello people", :ElementObject1 => elementObject},{:Elementtext2 => "hello world", :ElementObject2 => elementObject}] 

답변

1

같은 우리는 당신이 루트의 직접 아이들을 방문하기 때문에 traverse을 사용하는 모든 요소에 도달 할 수

require 'rubygems' 
require 'nokogiri' 

doc = Nokogiri::HTML(DATA.read) 

nodes = doc.root.css('.foo').collect do |n| 
    { :name => n.name, 
    :xpath => n.path, 
    :text => n.xpath('.//text()').collect{|t| 
     { :parent => t.parent.name, 
     :text => t.text }}} 
end 

p nodes 

__END__ 
<html> 
<body> 
<h1 class='foo'></h1> 
<p class='foo'>hello people<a href='http://'>hello world</a></p> 
</body> 
</html> 

이동합니다. 따라서 CSS selector를 사용하여 foo 클래스의 모든 요소를 ​​가져옵니다. 그리고 발견 된 각 요소에 대해 xpath selector를 사용하여 그 아래에있는 모든 텍스트 노드를 가져옵니다.

+0

많은 감사 애드리안 – Waheedi

관련 문제