【问题标题】:Remove all JavaScript from an HTML page从 HTML 页面中删除所有 JavaScript
【发布时间】:2012-01-07 16:08:52
【问题描述】:
我尝试使用 Sanitize gem 来清理包含网站 HTML 的字符串。
它只删除了<script>标签,而不是脚本标签中的JavaScript。
我可以使用什么来从页面中删除 JavaScript?
【问题讨论】:
标签:
ruby-on-rails
ruby
ruby-on-rails-3.1
screen-scraping
nokogiri
【解决方案1】:
我偏爱Loofah gem。根据文档中的示例修改:
1.9.3p0 :005 > Loofah.fragment("<span onclick='foo'>hello</span> <script>alert('OHAI')</script>").scrub!(:prune).to_s
=> "<span>hello</span> "
您可能对ActiveRecord extensions Loofah 提供的服务感兴趣。
【解决方案2】:
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
【解决方案3】:
原来Sanitize 有一个内置选项(只是没有很好的记录)...
Sanitize.clean(content, :remove_contents => ['script', 'style'])
这删除了我想要的所有脚本和样式标签(及其内容)。
【解决方案4】:
所以您需要将sanitize gem 添加到您的 Gemfile 中:
gem 'sanitize`
然后bundle
然后你就可以Sanitize.clean(text, remove_contents: ['script', 'style'])
【解决方案5】:
我使用这个正则表达式来去除嵌入内容中的<script> 和</script> 标签,让标签消失。它还消除了诸如< script> 或< /script > ...等之类的东西...即添加了空格。
post.content = post.content.gsub(/<\s*script\s*>|<\s*\/\s*script\s*>/, '')
【解决方案6】:
删除所有脚本标签
html_content = html_content.gsub(/<script.*?>[\s\S]*<\/script>/i, "")
source