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.textたいhello peoplehello worldのですが、それらをタグに関連付けます

結果は次のようになります

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

1 に答える 1

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セレクターを使用して、その下にあるすべてのテキストノードを取得します。

于 2009-12-07T16:00:18.097 に答える