【问题标题】:How to prevent Nokogiri from encoding entities in HTML fragments如何防止 Nokogiri 在 HTML 片段中编码实体
【发布时间】:2012-03-02 02:24:18
【问题描述】:

Nokogiri 1.5.0

我无法输出带有查询参数的链接的已解析片段,特别是在 href 中带有与号的链接。 & 符号被其 html 实体替换。

f = Nokogiri::HTML.fragment(%q{<a href="http://example.com?this=1&that=2">Testing</a>})
f.to_s    # => "<a href=\"http://example.com?this=1&amp;that=2\">Testing</a>"
f.to_html # => "<a href=\"http://example.com?this=1&amp;that=2\">Testing</a>"

使用 to_html(encoding: 'UTF-8') 或 US-ASCII 没有帮助。

这似乎很常见,解析有效的链接格式并希望将其呈现为有效的 HTML。

How to make Nokogiri transparently return un/encoded Html entities untouched? 没有帮助。

【问题讨论】:

    标签: html ruby nokogiri html-entities


    【解决方案1】:

    Nokogiri 的 HTML 解析器会自动纠正源文档中的错误。 URL 中的 & 符号是 actually an error,因此 Nokogiri 正在更正它。如果您查看f.errors,您会发现它认为&amp;that 不是有效实体并且缺少分号,因此它将与符号固定为&amp;amp;,使其成为有效的HTML。

    【讨论】:

    • 感谢您提供参考。
    猜你喜欢
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 2011-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-05
    • 1970-01-01
    相关资源
    最近更新 更多