使用 Nokogiri(而不是 Tidy)清理 HTML [英] Cleaning HTML with Nokogiri (instead of Tidy)
问题描述
tidy
gem 不再维护并且存在多个内存泄漏问题.
The tidy
gem is no longer maintained and has multiple memory leak issues.
有些人建议使用 Nokogiri.
Some people suggested using Nokogiri.
我目前正在使用以下方法清理 HTML:
I'm currently cleaning the HTML using:
Nokogiri::HTML::DocumentFragment.parse(html).to_html
我有两个问题:
Nokogiri 删除了
DOCTYPE
是否有一种简单的方法可以强制清理后的 HTML 具有 html
和 body
标签?
Is there an easy way to force the cleaned HTML to have a html
and body
tag?
推荐答案
如果您正在处理一个完整的文档,您需要:
If you are processing a full document, you want:
Nokogiri::HTML(html).to_html
这将强制使用 html
和 body
标签,并引入或保留 DOCTYPE
:
That will force html
and body
tags, and introduce or preserve the DOCTYPE
:
puts Nokogiri::HTML('<p>Hi!</p>').to_html
#=> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
#=> "http://www.w3.org/TR/REC-html40/loose.dtd">
#=> <html><body><p>Hi!</p></body></html>
puts Nokogiri::HTML('<!DOCTYPE html><p>Hi!</p>').to_html
#=> <!DOCTYPE html>
#=> <html><body><p>Hi!</p></body></html>
请注意,不保证输出在语法上是有效的.例如,如果我提供一个错误的文档并声称它是 HTML4.01 严格的,Nokogiri 将输出具有该 DOCTYPE 但没有所需的
部分:
Note that the output is not guaranteed to be syntactically valid. For example, if I provide a broken document that lies and claims that it is HTML4.01 strict, Nokogiri will output a document with that DOCTYPE but without the required <head><title>...</title></head>
section:
dtd = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">'
puts Nokogiri::HTML("#{dtd}<p>Hi!</p>").to_html
#=> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
#=> "http://www.w3.org/TR/html4/strict.dtd">
#=> <html><body><p>Hi!</p></body></html>
这篇关于使用 Nokogiri(而不是 Tidy)清理 HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!