您想要做的事情有些模棱两可,所以这是第一遍:
require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<div id="printready">
<div class="box-single"></div>
<div class="marker"></div>
<h2>sometext</h2>
<div id="news-single-img"></div>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<span class="cl"></span>
... (remove everything since the last paragraph)
</div>
EOT
%w[.box-single .marker].each do |klass|
doc.search(klass).each do |tag|
tag['class'] = nil
end
end
doc.at('h2').remove
%w[#news-single-img].each do |tag_id|
doc.at(tag_id)['id'] = nil
end
loop do
next_tag = doc.at('span.cl').next_sibling
break unless next_tag
next_tag.remove
end
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 id="printready">
<div class=""></div>
<div class=""></div>
<div id=""></div>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<span class="cl"></span>
</div></body></html>
如果要完全删除class
andid
参数:
require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)
<div id="printready">
<div class="box-single"></div>
<div class="marker"></div>
<h2>sometext</h2>
<div id="news-single-img"></div>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<span class="cl"></span>
... (remove everything since the last paragraph)
</div>
EOT
%w[.box-single .marker].each do |klass|
doc.search(klass).remove_attr('class')
end
doc.at('h2').remove
%w[#news-single-img].each do |tag_id|
doc.search(tag_id).remove_attr('id')
end
loop do
next_tag = doc.at('span.cl').next_sibling
break unless next_tag
next_tag.remove
end
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 id="printready">
<div></div>
<div></div>
<div></div>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<p>...</p>
<span class="cl"></span>
</div></body></html>