1

これを実行すると

Nokogiri::HTML('<div class="content"><p>Hello</p><p>Good Sir</p></div>').content

私はこれを得る

"HelloGood Sir"

NokogiriのAPIで以下を取得する方法はありますか?

"Hello Good Sir"
4

2 に答える 2

6
require 'nokogiri'

doc = Nokogiri::HTML('<div class="content"><p>Hello</p><p>Good Sir</p></div>')

# below will fetch all text nodes irrespective of any tag,from the current document.
doc.xpath("//text()").map(&:text)
# => ["Hello", "Good Sir"]

doc.xpath("//text()").map(&:text).join(" ")
# => "Hello Good Sir"

# below will fetch all text nodes which are wrapped inside the p tag,
# from the current document.
doc.xpath("//p").map(&:text)
# => ["Hello", "Good Sir"]

doc.xpath("//p").map(&:text).join(" ")
# => "Hello Good Sir"
于 2013-11-12T17:33:36.693 に答える
4

アラップが指摘したように

doc = Nokogiri::HTML('<div class="content"><p>Hello</p><p>Good Sir</p></div>')
doc.css('p').map(&:text).join(" ") #=> "Hello Good Sir"
于 2013-11-12T17:52:01.150 に答える