2011-05-23 100 views
14

我用nokogiri取消了一个html页面,我想剥去所有样式属性。
我该如何做到这一点? (我不使用轨道,所以我不能用它的sanitize方法,我不希望使用的sanitize宝石“因为我想黑名单中删除不白名单)nokogiri带状样式属性

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> 

我希望它是

=> <p><span>bla bla <a href="http://torrentfreak.com/netflix-is-killing-bittorrent-in-the-us-110427/">statistica</a> blabla</span></p> 

回答

15
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的,而不是一个文件,引入nokogiri具有a longstanding bug其中来自片段搜索你所期望不起作用。解决方法是使用:

doc.xpath('@style|.//@style').remove 
+0

哇。那很简单!我喜欢它。谢谢! – keepitterron 2011-05-25 08:14:16

+0

使用'doc.xpath('.//@style')。remove'从所有节点中删除所有内联样式,请注意下面的@bricker提到的'.'。链'.to_s'获取生成的html字符串。 – 2014-03-16 01:08:49

+0

更正:不要链接它,而是使用'description.to_s'来获得生成的html字符串。如果您不想使用'DOCTYPE',则应该使用'Nokogiri :: HTML.fragment'方法,请参阅http://stackoverflow.com/questions/4723344/how-to-prevent-nokogiri-from-adding- doctype-tags – 2014-03-16 01:17:15

3

我试图从Phrogz答案,但无法得到它的工作(我使用的是文档片段,虽然,但我还以为它应该工作一样吗?)。

开始处的“//”似乎没有像我期望的那样检查所有节点。最后我做了一些更长篇大论,但它的工作,所以这里的情况下,任何人的记录有相同的麻烦是我的解决方案(脏虽然它是):

doc = Nokogiri::HTML::Document.new 
body_dom = doc.fragment(my_html) 

# strip out any attributes we don't want 
body_dom.xpath('.//*[@align]|*[@align]').each do |tag| 
    tag.attributes["align"].remove 
end 

干杯

皮特

+1

这也可能起作用:'body_dom.xpath('.//@ class')'(请注意xpath开头处的额外点) – bricker 2013-01-29 21:24:25

+0

Nokogiri和/或LibXML2具有[XPath内部碎片](https://github.com/sparklemotion/nokogiri/issues/572)。当前最好的解决方法就像你注意到的那样:而不是'foo',你必须使用'foo | .// foo'。 – Phrogz 2014-03-16 02:22:17

8

这工作既具有文档和文档片段:

doc = Nokogiri::HTML::DocumentFragment.parse(...) 

doc = Nokogiri::HTML(...) 

要删除所有的 '风格' 属性,你可以做一个

doc.css('*').remove_attr('style')