如何使用Nokogiri替换外部标签

时间:2017-03-23 21:09:13

标签: ruby nokogiri

使用Nokogiri,我试图替换HTML节点的外部标签,其中最可靠的检测方式是通过其中一个孩子。

在:

<div>
    <div class="smallfont" >Quote:</div>
    Words of wisdom
</div>

后:

<blockquote>
    Words of wisdom
</blockquote>

以下代码段检测到我之后的元素,但我不确定如何从那里继续:

doc = Nokogiri::HTML(html)  

if doc.at('div.smallfont:contains("Quote:")') != nil
    q = doc.parent
    # replace tags of q
    # remove first_sibling
end

2 个答案:

答案 0 :(得分:1)

它运作正常吗?

doc = Nokogiri::HTML(html)
if quote = doc.at('div.smallfont:contains("Quote:")')
  text = quote.next # gets the '    Words of wisdom'
  quote.remove # removes div.smallfont
  puts text.parent.replace("<blockquote>#{text}</blockquote>") # replaces wrapping div with blockquote block
end

答案 1 :(得分:0)

我这样做:

require 'nokogiri'

doc = Nokogiri::HTML(DATA.read)

smallfont_div = doc.at('.smallfont')
smallfont_div.parent.name = 'blockquote'
smallfont_div.remove

puts doc.to_html 

__END__
<div>
    <div class="smallfont" >Quote:</div>
    Words of wisdom
</div>

结果是:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<blockquote>

    Words of wisdom
</blockquote>

</body></html>

浏览器显示时,<blockquote>内的空格会被浏览器吞噬,所以它通常不是问题,但有些浏览器仍会显示前导空格和/或尾随空间。

如果你想清理包含&#34;智慧之言的文本节点&#34;那我就这样做了:

smallfont_div = doc.at('.smallfont')
smallfont_parent = smallfont_div.parent
smallfont_div.remove
smallfont_parent.name = 'blockquote'
smallfont_parent.content = smallfont_parent.text.strip

结果是:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<blockquote>Words of wisdom</blockquote>
</body></html>

或者,这将产生相同的结果:

smallfont_div = doc.at('.smallfont')
smallfont_parent = smallfont_div.parent
smallfont_parent_content = smallfont_div.next_sibling.text
smallfont_parent.name = 'blockquote'
smallfont_parent.content = smallfont_parent_content.strip

代码的作用应该很容易理解,因为Nokogiri的方法非常明显。