2012-04-13 8 views
10

È possibile convertire HTML con Nokogiri in testo normale? Voglio anche includere il tag <br />.Convertire HTML in testo semplice (con inclusione di <br> s)

Ad esempio, dato questo HTML:

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

Voglio che questa uscita:

ala ma kota 
i kot to idiota 

Quando mi basta chiamare Nokogiri::HTML(my_html).text esclude <br /> tag:

ala ma kota i kot to idiota 
+1

un "dupa" gdzie? –

risposta

17

Invece di scrivere regexp complesso, ho usato Nokogiri.

Soluzione di lavoro (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

Eccellente, grazie. – AGS

8

Nulla di tutto questo esiste per impostazione predefinita, ma puoi facilmente modificare qualcosa che si avvicina all'uscita desiderata:

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

Prova

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

Nokogiri eliminerà pubblicitari, quindi utilizzare questo primo preservare collegamenti nella versione testo:

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

che trasformerà questo :

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

to questo:

link to google 
http://google.com 
0

Se si utilizza HAML si può risolvere html conversione mettendo html con l'opzione 'crudo', f.e.

 = raw @product.short_description 
Problemi correlati