繁体   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