Rails HTML 清理
我正在尝试清理 HTML 文件,但它无法正常工作。除了段落和换行符标签之外,我希望全部都是纯文本。这是我的清理代码(点表示我的类中与问题无关的其他代码):
.
.
.
include ActionView::Helpers::SanitizeHelper
.
.
.
def remove_html(html_content)
sanitized_content_1 = sanitize(html_content, :tags => %w(p br))
sanitized_content_2 = Nokogiri::HTML(sanitized_content_1)
sanitized_content_2.css("style","script").remove
return sanitized_content_2
end
它无法正常工作。 这是原始 HTML 文件,函数从中读取其输入, 和 这是它返回的“已清理”代码。它留在 CSS 标签、JavaScript 和 HTML 注释标签的正文中。它可能还留下了我没有注意到的其他东西。请告知如何彻底删除除段落和换行标记之外的所有 CSS、HTML 和 JavaScript?
I am trying to sanitize an HTML file and it isn't working correctly. I want to all be entirely plain text except for paragraph and line break tags. Here is my sanitization code (the dots signify other code in my class that isn't relevant to the problem):
.
.
.
include ActionView::Helpers::SanitizeHelper
.
.
.
def remove_html(html_content)
sanitized_content_1 = sanitize(html_content, :tags => %w(p br))
sanitized_content_2 = Nokogiri::HTML(sanitized_content_1)
sanitized_content_2.css("style","script").remove
return sanitized_content_2
end
It isn't working correctly. Here is the original HTML file from which the function is reading its input, and here is the "sanitized" code it is returning. It is leaving in the body of CSS tags, JavaScript, and HTML Comment Tags. It might be leaving in other stuff as well that I have not noticed. Please advise on how to thoroughly remove all CSS, HTML, and JavaScript other than paragraph and line break tags?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为你不想对其进行消毒。清理会去除 HTML,留下文本,但您认为正常的 HTML 元素除外。它的目的是允许用户输入字段包含一些标记。
相反,您可能想解析它。例如,下面的代码将打印给定 html 字符串中
标签的文本内容。
I don't think you want to sanitize it. Sanitizing strips HTML, leaving the text behind, except for the HTML elements you deem OK. It is intended for allowing a user-input field to contain some markup.
Instead, you probably want to parse it. For example, the following will print the text content of the
<p>
tags in a given html string.您也可以使用 CGI 命名空间进行清理。
运行这个脚本,我们得到以下结果。
You can sanitize with using CGI namespace too.
Run this script, we get following result.