将HTML转换为纯文本(包含)

是否可以将带有Nokogiri的HTML转换为纯文本? 我还想要包含
标签。

例如,给定此HTML:

 

ala ma kota


i kot to idiota

我想要这个输出:

 ala ma kota i kot to idiota 

当我只调用Nokogiri::HTML(my_html).text它会排除
标签:

 ala ma kota i kot to idiota 

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

工作解决方案(KISS!):

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

默认情况下不会出现这样的情况,但您可以轻松地将所需内容放在一起,接近所需的输出:

 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 "

It is the end of the world as we know it
and I feel fine.

Capische
Buddy?
" puts render_to_ascii(frag) #=> It is the end of the world as we know it #=> and I feel fine. #=> #=> Capische #=> ---------------------------------------------------------------------- #=> Buddy?

尝试

 Nokogiri::HTML(my_html.gsub('
',"\n")).text

Nokogiri将删除链接,因此我首先使用它来保留文本版本中的链接:

 html_version.gsub!(/(.*)<\/a>/i) { "#{$2}\n#{$1}" } 

这会改变这个:

 link to google 

对此:

 link to google http://google.com 

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

  = raw @product.short_description