Nokogiri#content
方法不会将块元素转换为段落;例如:
fragment = 'hell<span>o</span><p>world<p>I am Josh</p></p>'
Nokogiri::HTML(fragment).content
=> "helloworldI am Josh"
我期望输出:
=> "hellonnworldnnI am Josh"
如何将 html 转换为文本,确保块元素导致换行符并且内联元素被替换为没有空格?
您可以使用#before
和#after
添加换行符:
doc.search('p,div,br').each{ |e| e.after "n" }
这是我的解决方案:
fragment = 'hell<span>o</span><p>world<p>I am Josh</p></p>'
HtmlToText.process(fragment)
=> "hellonnworldnnI am Josh"
我遍历 nokogiri 树,边走边构建一个文本字符串,将文本包装在"nn"
中,用于块元素,""
内联元素。然后gsub
最后清理大量的n
字符。它很笨拙,但有效。
require 'nokogiri'
class HtmlToText
class << self
def process html
nokogiri = Nokogiri::HTML(html)
text = ''
nokogiri.traverse do |el|
if el.class == Nokogiri::XML::Element
sep = inline_element?(el) ? "" : "n"
if el.children.length <= 0
text += "#{sep}"
else
text = "#{sep}#{sep}#{text}#{sep}#{sep}"
end
elsif el.class == Nokogiri::XML::Text
text += el.text
end
end
text.gsub(/n{3,}/, "nn").gsub(/(An+)|(n+z)/, "")
end
private
def inline_element? el
el && el.try(:name) && inline_elements.include?(el.name)
end
def inline_elements
%w(
a abbr acronym b bdo big br button cite code dfn em i img input
kbd label map object q samp script select small span strong sub
sup textarea time tt var
)
end
end
end