当我运行它时
Nokogiri::HTML('<div class="content"><p>Hello</p><p>Good Sir</p></div>').content
我明白了
"HelloGood Sir"
有没有办法通过 Nokogiri 的 API 获取以下信息?
"Hello Good Sir"
最佳答案
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"
关于ruby - Nokogiri::HTML#content 中 HTML 元素之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935960/