10

のこぎりのあるHTMLをプレーンテキストに変換することはできますか? <br />タグも付けたいです。

たとえば、次の 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が除外されます:<br />

ala ma kota i kot to idiota
4

5 に答える 5

17

複雑な正規表現を書く代わりに Nokogiri を使いました。

実用的な解決策 (KISS!):

def strip_html(str)
  document = Nokogiri::HTML.parse(str)
  document.css("br").each { |node| node.replace("\n") }
  document.text
end
于 2012-04-16T12:48:52.840 に答える
8

このようなものはデフォルトでは存在しませんが、目的の出力に近いものを簡単に一緒にハックできます。

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?
于 2012-04-13T17:08:03.767 に答える
0

試す

Nokogiri::HTML(my_html.gsub('<br />',"\n")).text
于 2012-04-13T17:32:06.317 に答える
0

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
于 2012-04-13T17:57:04.657 に答える