簡體   English   中英

如何將HTML標記轉換為純文本?

[英]How do I convert HTML markup to just raw text?

Nokogiri::XML::DocumentFragment刪除所有標簽(僅保留文本,用空格分隔)的更簡單方法是什么?

我要轉換:

Hello<br>My name is McOmghall

變成:

Hello My name is McOmghall

我的解決方案是:

Nokogiri::XML.fragment(html_text).children.to_a.flatten.select { |node| node.class == Nokogiri::XML::Text}

然后串聯該數組,在每個元素之間放置空格,但是我認為它不是最優的,也不是很清楚。


編輯:

這是我的最終解決方案:

Nokogiri::XML.fragment(html_text).xpath('.//text()').map(&:text).join(' ')
root = Nokogiri::HTML('<div id="test">Hello<br>My name is McOmghall</div>')
root.at_css('#test').text
# => "HelloMy name is McOmghall"
root.at_css('#test').xpath('.//text()').map(&:text)
# => ["Hello", "My name is McOmghall"]
p root.at_css('#test').xpath('.//text()').map(&:text).join(' ')
# => "Hello My name is McOmghall"

Nokogiri有非常方便的方法text? 對於這種情況:

html = "Hello<br>My name is McOmghall"    

Nokogiri::HTML.fragment(html).children.select(&:text?).join(' ')
# => "Hello My name is McOmghall"

如果br之前或之后沒有空格,則文本中將沒有空格

doc = Nokogiri::HTML 'Hello<br>My name is McOmghall'
doc.text
#=> "HelloMy name is McOmghall"

不過,在每個br后面添加一個空格很容易:

doc.search('br').each{|br| br.after ' '}
doc.text
#=> "Hello My name is McOmghall"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM