2012-04-13 120 views
10

是否可以將HTML與Nokogiri轉換爲純文本?我也想包含<br />標籤。將HTML轉換爲純文本(包含<br> s)

例如,假設此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 
+1

a gdzie'dupa'? – 2015-11-16 13:48:36

回答

17

而不是寫複雜的正則表達式我用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 
+1

非常好,謝謝。 – AGS 2012-09-06 03:45:18

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

嘗試

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

引入nokogiri將去掉鏈接,所以我用這個先保存在文本版本的鏈接:

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

,這將關閉此:

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

to這個:

link to google 
http://google.com 
0

如果使用HAML你能解決HTML通過把HTML用 '原始' 選項,F.E.轉換

 = raw @product.short_description