wbh*_*ing 9 css ruby nokogiri css-parsing
我花了两个小时谷歌搜索这个,我找不到任何好的答案,所以让我们看看人类是否可以击败谷歌的电脑.
我想在Ruby中解析一个样式表,以便我可以将这些样式应用于我的文档中的元素(以使样式内联).所以,我想采取类似的东西
<style>
.mystyle {
  color:white;
}
</style>
并能够将其提取到某种Nokogiri对象中.
在引入nokogiri类"CSS ::分析器"(http://nokogiri.rubyforge.org/nokogiri/Nokogiri/CSS/Parser.html)肯定有前途的名字,但我找不到它是什么或如何任何文件它有效,所以我不知道它是否可以做我在这之后的事情.
我的最终目标是能够编写如下代码:
a_web_page = Nokogiri::HTML(html_page_as_string)
parsed_styles = Nokogiri::CSS.parse(html_page_as_string)
parsed_styles.each do |style| 
  existing_inlined_style = a_web_page.css(style.declaration) || ''
  a_web_page.css(style.declaration)['css'] = existing_inlined_style + style.definition
end
这将从样式表中提取样式,并将它们全部作为内联样式添加到我的文档中.
mol*_*olf 15
Nokogiri无法解析CSS样式表.
在CSS::Parser你遇到解析CSS 表达式.每当您通过CSS选择器而不是XPath遍历HTML树时都会使用它(这是Nokogiri的一个很酷的功能).
但是有一个Ruby CSS解析器.您可以将它与Nokogiri一起使用,以达到您想要的效果.
require "nokogiri"
require "css_parser"
html = Nokogiri::HTML(html_string)
css = CssParser::Parser.new
css.add_block!(css_string)
css.each_selector do |selector, declarations, specificity|
  element = html.css(selector)
  element["style"] = [element["style"], declarations].compact.join(" ")
end
@molf 确实有一个很好的开始,但仍然需要调试一些问题才能使其在生产中运行。这是当前经过测试的版本:
html = Nokogiri::HTML(html_string)
css = CssParser::Parser.new
css.add_block!(html_string) # Warning:  This line modifies the string passed into it.  In potentially bad ways.  Make sure the string has been duped and stored elsewhere before passing this.
css.each_selector do |selector, declarations, specificity|
  next unless selector =~ /^[\d\w\s\#\.\-]*$/ # Some of the selectors given by css_parser aren't actually selectors.
  begin
    elements = html.css(selector)
    elements.each do |match|
      match["style"] = [match["style"], declarations].compact.join(" ")
    end
  rescue
    logger.info("Couldn't parse selector '#{selector}'")
  end
end
html_with_inline_styles = html.to_s