Ruby on rails 从HTML页面中删除所有JavaScript

Ruby on rails 从HTML页面中删除所有JavaScript,ruby-on-rails,ruby,ruby-on-rails-3.1,screen-scraping,nokogiri,Ruby On Rails,Ruby,Ruby On Rails 3.1,Screen Scraping,Nokogiri,我尝试使用清理gem清理包含网站HTML的字符串 它只删除了标记,而没有删除脚本标记中的JavaScript 我可以用什么来删除页面中的JavaScript?我偏爱gem。根据文档中的示例修改: 1.9.3p0 :005 > Loofah.fragment("<span onclick='foo'>hello</span> <script>alert('OHAI')</script>").scrub!(:prune).to_s =>

我尝试使用
清理
gem清理包含网站HTML的字符串

它只删除了
标记,而没有删除脚本标记中的JavaScript

我可以用什么来删除页面中的JavaScript?

我偏爱gem。根据文档中的示例修改:

1.9.3p0 :005 > Loofah.fragment("<span onclick='foo'>hello</span> <script>alert('OHAI')</script>").scrub!(:prune).to_s
 => "<span>hello</span> " 
1.9.3p0:005>丝瓜碎片(“你好警报('OHAI'))。擦洗!(:修剪)
=>“你好”
您可能对丝瓜提供的服务感兴趣。

需要Ruby附带的“开放uri”;只需要从URL加载HTML
require 'open-uri'      # included with Ruby; only needed to load HTML from a URL
require 'nokogiri'      # gem install nokogiri   read more at http://nokogiri.org

html = open('http://stackoverflow.com')              # Get the HTML source string
doc = Nokogiri.HTML(html)                            # Parse the document

doc.css('script').remove                             # Remove <script>…</script>
puts doc                                             # Source w/o script blocks

doc.xpath("//@*[starts-with(name(),'on')]").remove   # Remove on____ attributes
puts doc                                             # Source w/o any JavaScript
需要“nokogiri”#gem安装nokogiri更多信息请访问http://nokogiri.org html=打开('http://stackoverflow.com')#获取HTML源字符串 doc=Nokogiri.HTML(HTML)#解析文档 doc.css('script')。删除#删除… 放置文档#不带脚本块的源 doc.xpath(“/@*[以(name(),'on')]开头]”).remove#remove on___;属性 放置文档#源代码,不带任何JavaScript
事实证明,
消毒
有一个内置选项(只是没有很好的文档记录)


这删除了我想要的所有脚本和样式标记(及其内容)。

因此您需要将
清理
gem添加到您的gem文件中:

gem 'sanitize`
然后
bundle


然后您可以执行清理(text,remove_contents:['script','style'])

我使用这个正则表达式来去除嵌入内容中的
标记,并使标记消失。它还消除了诸如
等内容。。。i、 e.添加空格

post.content=post.content.gsub(/|/,“”)

删除所有脚本标记
html\u content=html\u content.gsub(/[\s\s]*/i,”)

是否还要删除*
属性上的所有
?如果您的目的是防止XSS攻击,那么这似乎是一个非常糟糕的主意。你错过了各种各样的边缘案例。
gem 'sanitize`
html_content = html_content.gsub(/<script.*?>[\s\S]*<\/script>/i, "")