16

我正在用 nokogiri 抓取一个 html 页面,我想去掉所有样式属性。
我怎样才能做到这一点?(我没有使用 Rails,所以我不能使用它的 sanitize 方法,我不想使用 sanitize gem,因为我想将黑名单删除而不是白名单)

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>
4

3 回答 3

19
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 存在一个长期存在的错误,即从片段中搜索无法按预期工作。解决方法是使用:

doc.xpath('@style|.//@style').remove
于 2011-05-23T22:26:25.823 回答
8

这适用于文档和文档片段:

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

或者

doc = Nokogiri::HTML(...)

要删除所有“样式”属性,您可以执行

doc.css('*').remove_attr('style')
于 2014-10-08T01:50:24.640 回答
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
于 2012-07-11T10:03:26.127 回答