微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 带nokogiri的条带样式属性

我正在使用nokogiri擦除一个html页面,我想删除所有的样式属性.
我该如何实现? (我不使用rails,所以我不能使用它的消毒方法,我不想使用消毒宝石’因为我想黑名单删除不是白名单)
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>

解决方法

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,其中从片段中进行搜索不会按预期的方式工作.解决方法是使用:

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

原文地址:https://www.jb51.cc/html/230352.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐