【问题标题】:How to use Nokogiri::HTML.fragment without creating unwanted custom tags如何在不创建不需要的自定义标签的情况下使用 Nokogiri::HTML.fragment
【发布时间】:2019-09-19 10:09:07
【问题描述】:

我有支持 Nokogiri 的 HTML 分段的 Ruby 代码。

当用户向应用程序输入带有"<" 的文本时,Nokogiri::HTML.fragment 会将其添加到自定义 HTML 标记中。

如果用户输入类似的文字

"One <two three"

应用程序会像这样显示它

"one <two three></two>"

我正在使用Nokogiri::HTML.fragment(html, encoding = 'UTF-8')

有人知道怎么解决吗?

【问题讨论】:

  • 你能给出一个清楚的例子来说明你想要达到的目标吗?示例输入和预期输出。
  • 目前我的输入是“一二>”,预期输出是“一. 这样的自定义 html 标签
  • 不要在评论中添加说明,而是将其添加到您的问题中,就像您最初包含它一样,没有“已编辑”或一些此类标记。评论是为了要求澄清并向提出问题的人提供信息。

标签: html ruby-on-rails ruby nokogiri


【解决方案1】:

您不了解 HTML 与解析器的文本有何不同。 Nokogiri 认为 one &lt;two three 是 HTML 并尝试验证它,看到 &lt;two three 并认为它是一个标签 &lt;two 后跟一个参数,但没有看到结束 &gt; 所以它做了一些修复尝试乐于助人。

require 'nokogiri'

doc = Nokogiri::HTML::DocumentFragment.parse('one <two three') 
doc.to_html # => "one <two three></two>"

相反,就像您要创建一个包含one &lt;two three 的页面一样,您必须提供 HTML 编码文本:

doc = Nokogiri::HTML::DocumentFragment.parse('one &lt;two three') 
doc.to_html # => "one &lt;two three"

您可以使用 HTML 实体 gem 自动执行此操作:

require 'htmlentities'
coder = HTMLEntities.new

doc = Nokogiri::HTML::fragment(coder.encode('one <two three'))
doc.to_html # => "one &lt;two three"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2023-04-07
    • 2021-10-17
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多