在Ruby中寻找CSS解析器

时间:2011-03-01 23:26:44

标签: html css ruby parsing html-parsing

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

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

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

我已经用Google搜索了,我也在这里搜索过Stackoverflow,但我能找到的就是这个Java解析器。

2 个答案:

答案 0 :(得分:6)

我还需要一个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"}]

答案 1 :(得分:3)

您有几个选项,例如......