是否存在类似于HTML tidy(http://tidy.sourceforge.net/)的库,它不是特定于操作系统的(需要在每个主机上编译).基本上我只想验证/清理用户发送给我的HTML.
谢谢!
<p>hello</p></p><br>@H_403_4@应该成为
<p>hello</p> <br/>@H_403_4@javascript或ruby中的东西对我有用.
谢谢!
解决方法
在Ruby中,您可以解析Nokogiri中的HTML,它可以让您检查错误,然后输出HTML,这将清除丢失的结束标记等.请注意,在以下HTML中,title和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>@H_403_4@或者,您可以打开与/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>