Ruby:清理 HTML、使用 Hpricot 还是仅使用正则表达式?
我希望对 HTML 进行一些基本的清理。基本上想要创建一个允许的标签白名单并拒绝其他任何内容。
在这种情况下,Hpricot 值得吗?它是否有一个我忽略的功能可以让我免于重写轮子?或者最好只使用正则表达式编写标签白名单并通过它来处理 HTML 文档?
正则表达式对于 HTML 来说可能会变得非常棘手,而且我知道很多专家都强烈反对它 - 我只是在寻找阻力最小的路径。
I'm looking to do some rudimentary cleansing of HTML. Basically want to create a whitelist of tags that are allowed and reject anything else.
Is Hpricot worth it in this case? Does it have a feature that I've overlooked that will save me from rewriting the wheel? Or is it best to just write a whitelist of tags using regex and massage an HTML document through that?
Regex can get really tricky with HTML, and I know a lot of experts are strictly against it - I'm just looking for the path of least resistance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
阻力最小的路径一开始可能看起来是正则表达式,但是当您通过它提供更多文本时,您会意识到它一次又一次地中断,并为您带来更多工作。这就是为什么有经验的程序员知道使用 XML/DOM 解析器来解决这样的常见问题。
我建议您使用 Nokogiri 而不是 Hpricot,因为它更快且维护得更好。
https://github.com/rgrove/sanitize/
Sanitize 使用 Nokogiri 来完成您正在做的事情。
The path of least resistance may seem to be a regex at first, but then as you feed more text through it, you realize that it breaks again and again and makes more work for you. That is why experienced programmers know to use XML/DOM parsers for such a common problem.
I recommend that you use Nokogiri and not Hpricot though because it is faster and better maintained.
https://github.com/rgrove/sanitize/
Sanitize uses Nokogiri to do exactly what you are doing.