【问题标题】:Convert HTML to plain text (with inclusion of <br>s)将 HTML 转换为纯文本(包含 <br>s)
【发布时间】:2018-05-15 22:40:09
【问题描述】:

是否可以将带有 Nokogiri 的 HTML 转换为纯文本?我还想包含&lt;br /&gt; 标签。

例如,给定以下 HTML:

<p>ala ma kota</p> <br /> <span>i kot to idiota </span>

我想要这个输出:

ala ma kota
i kot to idiota

当我只调用Nokogiri::HTML(my_html).text 时,它不包括&lt;br /&gt; 标签:

ala ma kota i kot to idiota

【问题讨论】:

    标签: ruby nokogiri


    【解决方案1】:

    我没有编写复杂的正则表达式,而是使用 Nokogiri。

    工作解决方案(K.I.S.S!):

    def strip_html(str)
      document = Nokogiri::HTML.parse(str)
      document.css("br").each { |node| node.replace("\n") }
      document.text
    end
    

    【讨论】:

      【解决方案2】:

      默认情况下不存在类似的东西,但您可以轻松地将接近所需输出的东西组合在一起:

      require 'nokogiri'
      def render_to_ascii(node)
        blocks = %w[p div address]                      # els to put newlines after
        swaps  = { "br"=>"\n", "hr"=>"\n#{'-'*70}\n" }  # content to swap out
        dup = node.dup                                  # don't munge the original
      
        # Get rid of superfluous whitespace in the source
        dup.xpath('.//text()').each{ |t| t.content=t.text.gsub(/\s+/,' ') }
      
        # Swap out the swaps
        dup.css(swaps.keys.join(',')).each{ |n| n.replace( swaps[n.name] ) }
      
        # Slap a couple newlines after each block level element
        dup.css(blocks.join(',')).each{ |n| n.after("\n\n") }
      
        # Return the modified text content
        dup.text
      end
      
      frag = Nokogiri::HTML.fragment "<p>It is the end of the world
        as         we
        know it<br>and <i>I</i> <strong>feel</strong>
        <a href='blah'>fine</a>.</p><div>Capische<hr>Buddy?</div>"
      
      puts render_to_ascii(frag)
      #=> It is the end of the world as we know it
      #=> and I feel fine.
      #=> 
      #=> Capische
      #=> ----------------------------------------------------------------------
      #=> Buddy?
      

      【讨论】:

        【解决方案3】:

        试试

        Nokogiri::HTML(my_html.gsub('<br />',"\n")).text
        

        【讨论】:

          【解决方案4】:

          Nokogiri 会去掉链接,所以我先用这个来保留文本版本中的链接:

          html_version.gsub!(/<a href.*(http:[^"']+).*>(.*)<\/a>/i) { "#{$2}\n#{$1}" }
          

          这会变成这样:

          <a href = "http://google.com">link to google</a>
          

          到这里:

          link to google
          http://google.com
          

          【讨论】:

            【解决方案5】:

            如果您使用 HAML,则可以通过将 html 与 'raw' 选项 f.e. 放在一起来解决 html 转换问题

                  = raw @product.short_description
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2012-04-12
              • 2014-09-08
              • 2012-01-15
              • 2018-03-17
              • 1970-01-01
              • 2014-04-21
              • 1970-01-01
              相关资源
              最近更新 更多