【问题标题】:Spaces inbetween HTML elements in Nokogiri::HTML#contentNokogiri::HTML#content 中 HTML 元素之间的空格
【发布时间】:2013-11-12 17:30:54
【问题描述】:

当我运行它时

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

我明白了

"HelloGood Sir"

有没有办法通过 Nokogiri 的 API 获得以下内容?

"Hello Good Sir"

【问题讨论】:

    标签: ruby nokogiri


    【解决方案1】:
    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"
    

    【讨论】:

    • 两个答案都很棒,我选择了这个 b/c,它不需要嵌套 html 标签的知识。谢谢!
    【解决方案2】:

    就像奥雅纳指出的那样

    doc = Nokogiri::HTML('<div class="content"><p>Hello</p><p>Good Sir</p></div>')
    doc.css('p').map(&:text).join(" ") #=> "Hello Good Sir"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      相关资源
      最近更新 更多