如何使用 Nokogiri 替换文本字符串"inner_html"



我想获取一个 HTML 字符串并返回一个保留 HTML 结构但带有混淆文本/内部 HTML 的突变版本。

例如:

string = "<div><p><h1>this is some sensitive text</h1><br></p><p>more text</p></div>"
obfuscate_html_string(string)
=> "<div><p><h1>**** **** **** **** ****</h1><br></p><p>**** ****</p></div>"

我进行了实验,虽然看起来inner_html=方法可能很有用,但它引发了一个参数错误:

Nokogiri::HTML.fragment(value).traverse { |node| node.content = '***' if node.inner_html }.to_s
=> "***"
Nokogiri::HTML.fragment(value).traverse { |node| node.content ? node.content = '***' : node.to_html }.to_s
=> "***"
Nokogiri::HTML.fragment(value).traverse { |node| node.inner_html = '***' if node.inner_html }.to_s
=> ArgumentError: cannot reparent Nokogiri::XML::Text there

这应该会有所帮助,但文档对此进行了更详细的介绍。

你的HTML有问题,因为它是无效的,这迫使Nokogiri进行修复,此时这将改变HTML:

require 'nokogiri'
doc = Nokogiri::HTML("<div><p><h1>this is some sensitive text</h1><br></p><p>more text</p></div>")
doc.errors # => [#<Nokogiri::XML::SyntaxError: 1:53: ERROR: Unexpected end tag : p>]
doc.to_html
# => "<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">n" +
#    "<html><body><div>n" +
#    "<p></p>n" +
#    "<h1>this is some sensitive text</h1>n" +
#    "<br><p>more text</p>n" +
#    "</div></body></html>n"

Nokogiri 报告说 HTML 中存在错误,因为您无法在p中嵌套h1标签:

ERROR: Unexpected end tag : p>

这意味着它无法理解 HTML,并尽最大努力通过提供/更改结束标记来恢复,直到它对它有意义。这并不意味着HTML实际上是你或作者想要的。

从那时起,您查找节点的尝试可能会失败,因为 DOM 已更改。

始终检查errors,如果它不为空,请非常小心。最好的解决方案是通过Tidy或类似的东西运行该HTML,然后处理其输出。

不过,从这一点来看,这应该有效:

node = doc.at('div h1')
node.inner_html = node.inner_html.tr('a-z', '*')
node = doc.search('div p')[1]
node.inner_html = node.inner_html.tr('a-z', '*')
puts doc.to_html
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> <html><body><div>
# >> <p></p>
# >> <h1>**** ** **** ********* ****</h1>
# >> <br><p>**** ****</p>
# >> </div></body></html>

最新更新