【问题标题】:HTML tidy/cleaning in Ruby 1.9Ruby 1.9 中的 HTML 整理/清理
【发布时间】:2009-08-20 20:46:01
【问题描述】:

我目前正在使用 RubyTidy Ruby 绑定 HTML tidy 以确保我收到的 HTML 格式正确。目前这个库是唯一阻碍我在 Ruby 1.9 上获得 Rails 应用程序的东西。是否有任何替代库可以整理 Ruby 1.9 上的 HTML 块?

【问题讨论】:

    标签: html ruby-1.9 tidy


    【解决方案1】:

    http://github.com/libc/tidy_ffi/blob/master/README.rdoc 适用于 ruby​​ 1.9(最新版本)

    如果你在windows上工作,你需要设置library_path eg

        require 'tidy_ffi'
        TidyFFI.library_path = 'lib\\tidy\\bin\\tidy.dll'
        tidy = TidyFFI::Tidy.new('test')
        puts tidy.clean
    

    (它使用与tidy相同的dll)以上链接为您提供了更多用法示例。

    【讨论】:

      【解决方案2】:

      我正在使用Nokogiri 来修复无效的html:

      Nokogiri::HTML::DocumentFragment.parse(html).to_html

      【讨论】:

      • 我认为这不会整理 HTML。
      • 可靠吗?我的意思是,它是否修复了语法错误,例如段落中的嵌套列表?
      • Nokogiri 仅确保 html 格式正确,但不会修复语法错误。例如,<table>x<table>y 被“固定”成<table>x<table>y</table></table>
      【解决方案3】:

      这是一个很好的例子,说明如何使用 tidy 让你的 html 看起来更好:

      require 'tidy'
      Tidy.path = '/opt/local/lib/libtidy.dylib' # or where ever your tidylib resides
      
      nice_html = ""
      Tidy.open(:show_warnings=>true) do |tidy|
        tidy.options.output_xhtml = true
        tidy.options.wrap = 0
        tidy.options.indent = 'auto'
        tidy.options.indent_attributes = false
        tidy.options.indent_spaces = 4
        tidy.options.vertical_space = false
        tidy.options.char_encoding = 'utf8'
        nice_html = tidy.clean(my_nasty_html_string)
      end
      
      # remove excess newlines
      nice_html = nice_html.strip.gsub(/\n+/, "\n")
      puts nice_html
      

      如需更整洁的选项,请查看man page

      【讨论】:

      • 到目前为止,tidy gem 似乎与 Ruby 1.9 不兼容。 github.com/ShogunPanda/tidy 似乎有一个分叉,但我没有调查它。
      【解决方案4】:

      目前只有这个库 阻碍我获得 Ruby 1.9 上的 Rails 应用程序。

      注意,Ruby Tidy 绑定有一些严重的内存泄漏。它目前无法在长时间运行的进程中使用。 (为了记录,我使用的是http://github.com/ak47/tidy

      我只需要从生产 Rails 2.3 应用程序中删除它,因为它的泄漏速度约为 1MB/分钟。

      【讨论】:

        猜你喜欢
        • 2012-07-13
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 2011-03-05
        • 2012-04-13
        • 1970-01-01
        • 1970-01-01
        • 2016-10-16
        相关资源
        最近更新 更多