ruby 使用Nokogiri,如何将html转换为文本尊重块元素(确保它们导致换行符)

kknvjkwl  于 2023-05-17  发布在  Ruby
关注(0)|答案(2)|浏览(143)

Nokogiri #content方法不会将块元素转换为段落;例如:

fragment = 'hell<span>o</span><p>world<p>I am Josh</p></p>'
Nokogiri::HTML(fragment).content
=> "helloworldI am Josh"

我希望输出:

=> "hello\n\nworld\n\nI am Josh"

如何将html转换为文本,确保块元素导致换行符和行内元素被替换为没有空格?

6jjcrrmo

6jjcrrmo1#

你可以使用#before#after来添加新行:

doc.search('p,div,br').each{ |e| e.after "\n" }
toiithl6

toiithl62#

这是我的解决方案:

fragment = 'hell<span>o</span><p>world<p>I am Josh</p></p>'
HtmlToText.process(fragment)
=> "hello\n\nworld\n\nI am Josh"

我遍历nokogiri树,构建一个文本字符串,对于块元素用"\n\n" Package 文本,对于行内元素用"" Package 文本。然后使用gsub来清除最后\n字符的丰度。有点古怪但很管用。

require 'nokogiri'

class HtmlToText
  class << self
    def process html
      nokogiri = Nokogiri::HTML(html)
      text = ''
      nokogiri.traverse do |el|
        if el.class == Nokogiri::XML::Element
          sep = inline_element?(el) ? "" : "\n"
          if el.children.length <= 0
            text += "#{sep}"
          else 
            text = "#{sep}#{sep}#{text}#{sep}#{sep}"
          end
        elsif el.class == Nokogiri::XML::Text
          text += el.text
        end
      end
      text.gsub(/\n{3,}/, "\n\n").gsub(/(\A\n+)|(\n+\z)/, "")
    end

    private

    def inline_element? el
      el && el.try(:name) && inline_elements.include?(el.name)
    end

    def inline_elements
      %w(
        a abbr acronym b bdo big br button cite code dfn em i img input
        kbd label map object q samp script select small span strong sub
        sup textarea time tt var
      )
    end
  end
end

相关问题