html - 在 Ruby 中寻找 CSS 解析器

标签 html css ruby parsing html-parsing

<分区>

我正在寻找一个 CSS 解析器,类似于这个 Looking for a CSS Parser in java , 但在 Ruby 中。

输入:HTML 文档的一个元素。

输出:与该特定元素关联的所有样式。

我用谷歌搜索过,我也在 Stackoverflow 上搜索过,但我能找到的只是这个 Java 解析器。

最佳答案

我还需要一个 CSS 解析器,但接受的答案中列出的都不能解析 CSS3。

我结束了对 Sass 的一点扩展:

require 'sass'

class Sass::Tree::Visitors::ToArray < Sass::Tree::Visitors::Base
  protected

  def initialize
    @array = []
  end

  def visit(node, parent = false)
    if node_name(parent) == "root"
      @media = "all"
    end

    method = "visit_#{node_name(node)}"

    if self.respond_to?(method, true)
      self.send(method, node)
    else
      visit_children(node)
    end

    @array
  end

  def visit_children(parent)
    parent.children.map {|c| visit(c, parent)}
  end

  def visit_root(node)
    visit_children(node)
  end

  def visit_media(node)
    @media = node.query.join('')
    visit_children(node)
  end

  def visit_rule(node)
    @selector = node.rule[0]
    visit_children(node)
  end

  def visit_prop(node)
    return unless node.value

    @array << {
      media: @media,
      selector: @selector,
      property: node.name[0],
      value: node.value.to_sass
    }
  end
end

class Sass::Tree::Node
  def to_a
    Sass::Tree::Visitors::ToArray.visit(self)
  end
end

通过上面的代码,

Sass::Engine.new("body {color: #f00}, p {font-size: 20px}", :syntax => :scss).to_tree.to_a

会导致

> [{:media=>:all, :selector=>"body", :property=>"color", :value=>"#f00"}, {:media=>:all, :selector=>"p", :property=>"font-size", :value=>"20px"}]

关于html - 在 Ruby 中寻找 CSS 解析器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5161681/

相关文章:

html - 在列表标签​​之间放置 DIV 标签是否有效?

LESS 中的 Javascript 显得步履蹒跚 : workaround?

css - 为什么 Compass CSS Blueprint 中有右边距?

ruby - 在 ruby​​ 中发送和接收 TCP 数据

html - 横幅图片在移动设备上没有响应

javascript - 将 JS 代码从 NodeJS HTML 文件导出到 JS 文件

jquery - 使用 css3 变换时重叠,任何防止这种情况的方法

ruby - 使用 Ruby 在多个操作系统中读取文件名而没有编码问题

ruby - pythonchallenge.com 4 in ruby​​ 解决方案

javascript - 链式选择提交按钮已停止正常运行