【问题标题】:Remove all JavaScript from an HTML page从 HTML 页面中删除所有 JavaScript
【发布时间】:2012-01-07 16:08:52
【问题描述】:

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

它只删除了<script>标签,而不是脚本标签中的JavaScript。

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

【问题讨论】:

  • 您还想删除所有on* 属性吗?

标签: 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】:

        我使用这个正则表达式来去除嵌入内容中的&lt;script&gt;&lt;/script&gt; 标签,让标签消失。它还消除了诸如&lt; script&gt;&lt; /script &gt; ...等之类的东西...即添加了空格。

        post.content = post.content.gsub(/&lt;\s*script\s*&gt;|&lt;\s*\/\s*script\s*&gt;/, '')

        【讨论】:

          【解决方案6】:

          删除所有脚本标签

          html_content = html_content.gsub(/<script.*?>[\s\S]*<\/script>/i, "")
          

          source

          【讨论】:

            猜你喜欢
            • 2015-09-16
            • 1970-01-01
            • 2016-04-06
            • 2015-08-14
            • 1970-01-01
            • 2017-02-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多