我正在使用nokogiri擦除一个html页面,我想删除所有的样式属性.
我该如何实现? (我不使用rails,所以我不能使用它的消毒方法,我不想使用消毒宝石’因为我想黑名单删除不是白名单) @H_404_3@html = open(url) doc = Nokogiri::HTML(html.read) doc.css('.post').each do |post| puts post.to_s end => <p><span style="font-size: x-large">bla bla <a href="http://torrentfreak.com/netflix-is-killing-bittorrent-in-the-us-110427/">statistica</a> blabla</span></p>
我该如何实现? (我不使用rails,所以我不能使用它的消毒方法,我不想使用消毒宝石’因为我想黑名单删除不是白名单) @H_404_3@html = open(url) doc = Nokogiri::HTML(html.read) doc.css('.post').each do |post| puts post.to_s end => <p><span style="font-size: x-large">bla bla <a href="http://torrentfreak.com/netflix-is-killing-bittorrent-in-the-us-110427/">statistica</a> blabla</span></p>
我想要它
@H_404_3@=> <p><span>bla bla <a href="http://torrentfreak.com/netflix-is-killing-bittorrent-in-the-us-110427/">statistica</a> blabla</span></p>解决方法
@H_404_3@require 'nokogiri'
html = '<p class="post"><span style="font-size: x-large">bla bla</span></p>'
doc = Nokogiri::HTML(html)
doc.xpath('//@style').remove
puts doc.css('.post')
#=> <p class="post"><span>bla bla</span></p>
编辑显示您可以调用NodeSet#remove
而不必使用.each(&:remove).
请注意,如果您有DocumentFragment而不是Document,则Nokogiri有a longstanding bug,其中从片段中进行搜索不会按预期的方式工作.解决方法是使用:
@H_404_3@doc.xpath('@style|.//@style').remove