如何使用 Nokogiri 删除重复的嵌套标签



我有带有嵌套重复标签的 HTML:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<div>
<div>
<p>Some text</p>
</div>  
</div>
</div>
</body>
</html> 

我想删除没有任何属性的嵌套重复div。生成的 HTML 应如下所示:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<p>Some text</p>
</div>  
</body>
</html> 

如何使用 Nokogiri 或纯 Ruby 来完成呢?

通常我不是像Nokogiri那样的可变结构的忠实粉丝,但在这种情况下,我认为它对您有利。像这样的东西可能会起作用:

def recurse node
# depth first so we don't accidentally modify a collection while
# we're iterating through it.
node.elements.each do |child|
recurse(child)
end
# replace this element's children with it's grandchildren
# assuming it meets all the criteria
if merge_candidate?(node)
node.children = node.elements.first.children
end
end
def merge_candidate? node, name: 'div'
return false unless node.element?
return false unless node.attributes.empty?
return false unless node.name == name
return false unless node.elements.length == 1
return false unless node.elements.first.name == name
return false unless node.elements.first.attributes.empty?
true
end
[18] pry(main)> file = File.read('test.html')
[19] pry(main)> doc = Nokogiri.parse(file)
[20] pry(main)> puts doc
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<div>
<div>
<p>Some text</p>
</div>  
</div>
</div>
</body>
</html>
[21] pry(main)> recurse(doc)
[22] pry(main)> puts doc
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<p>Some text</p>
</div>
</body>
</html>
=> nil
[23] pry(main)> 

根据你的HTML结构,这应该会让你开始:

require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<div>
<div>
<p>Some text</p>
</div>  
</div>
</div>
</body>
</html> 
EOT
dd = doc.at('div div').parent
dp = dd.at('div p')
dd.children.unlink
dp.parent = dd

这导致:

puts doc.to_html
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> <html>
# >>   <head>
# >>     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
# >>   </head>
# >>   <body>
# >>     <div><p>Some text</p></div>
# >>   </body>
# >> </html>

dd是两个连续div标签的parent,换句话说,它是链中的第一个div

dp是该链末端的p节点。

dd.children是一个包含ddchildren的节点集,一直到并包括dp

这个想法是在删除所有其他干预<div>标签后,将dp(所需的<p>节点(嫁接到dd(最顶层的<div>节点(。通过节点集,可以轻松地一次unlink大量标签。

阅读有关at以了解为什么它对此类问题很重要。

最新更新