是否有“HTML tidy”的 JavaScript 或 Ruby 版本? [关闭]

2023-11-30

是否存在类似于 HTML tidy (http://tidy.sourceforge.net/) 的库,该库不是特定于操作系统的(需要在每个主机上编译)。基本上我只是想验证/清理用户发送给我的 HTML。

<p>hello</p></p><br>

应该成为

<p>hello</p>
<br/>

javascript 或 ruby​​ 中的东西对我有用。 谢谢!


在 Ruby 中,您可以在 Nokogiri 中解析 HTML,这将让您检查错误,然后让它输出 HTML,这将清理丢失的结束标记等。请注意,在以下 HTML 中,标题和 p 标签未正确关闭,但 Nokogiri 添加了结束标签。

require 'nokogiri'

html = '<html><head><title>the title</head><body><p>a paragraph</body></html>'
doc = Nokogiri::HTML(html)
puts "Errors found" if (doc.errors.any?)
puts doc.to_html
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> <html>
# >> <head>
# >> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
# >> <title>the title</title>
# >> </head>
# >> <body><p>a paragraph</p></body>
# >> </html>

或者,您可以打开一个连接/usr/bin/tidy并告诉它做肮脏的工作:

require 'open3'

html = '<html><head><title>the title</head><body><p>a paragraph</body></html>'

stdin, stdout, stderr = Open3.popen3('/usr/bin/tidy -qi')
stdin.puts html
stdin.close
puts stdout.read
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
# >> 
# >> <html>
# >> <head>
# >>   <meta name="generator" content=
# >>   "HTML Tidy for Mac OS X (vers 31 October 2006 - Apple Inc. build 15.3.6), see www.w3.org">
# >> 
# >>   <title>the title</title>
# >> </head>
# >> 
# >> <body>
# >>   <p>a paragraph</p>
# >> </body>
# >> </html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是否有“HTML tidy”的 JavaScript 或 Ruby 版本? [关闭] 的相关文章

随机推荐