2009-12-06 23 views
1

比方说,我有这样的例子:引入nokogiri如何获取父文本,而不是孩子的文本和参考文本回其父

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

有我们去

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> 

使用traverse,因为它仅访问根的直接孩子你不能达到的所有元素。因此,我使用css选择器来获取类foo的所有元素。然后,对于每个找到的元素,我使用xpath选择器来获取它下面的所有文本节点。

+0

非常感谢adrian – Waheedi 2009-12-08 11:07:10

相关问题