2012-04-13 9 views
10

¿Es posible convertir HTML con Nokogiri en texto sin formato? También quiero incluir la etiqueta <br />.Convierta HTML a texto sin formato (con inclusión de <br> s)

Por ejemplo, teniendo en cuenta este código HTML:

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

Quiero esta salida:

ala ma kota 
i kot to idiota 

Cuando acabo de llamar Nokogiri::HTML(my_html).text excluye <br /> etiqueta:

ala ma kota i kot to idiota 
+1

a gdzie 'dupa'? –

Respuesta

17

En lugar de escribir la expresión compleja, utilicé Nokogiri.

Solución de trabajo (K.I.S.S!):

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

Excelente, gracias. – AGS

8

Nada como esto existe de forma predeterminada, pero puede hackear fácilmente algo que se acerca a la salida deseada:

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? 
0

Trate

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

Nokogiri eliminará los enlaces, así que utilice este primer preservar los eslabones de la versión de texto:

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

que convertirá este :

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

to esto:

link to google 
http://google.com 
0

Si utiliza HAML puede resolver html convertir poniendo html con la opción 'en bruto', F. E.

 = raw @product.short_description 
Cuestiones relacionadas