2

获取元素的渲染样式 (也应该能够处理内联 CSS)

我一直在学习Nokogiri并了解如何根据 ID 或类选择节点。但是,我想选择一个节点/元素并取回分配给它的特定 CSS 样式,包括继承的样式。

CSS 样式表:

<head>
  <style type="text/css">
    .myfont {font-family: Times New Roman: font-size: 80% }
    .bold {font-weight: bold}
    .50_font_size { font-size:50% }
   </style>
 </head>

HTML:

<Body>
   <div id="article1" class="myfont">
      <div id="title1" class="bold">  
          My Title Text
          <div id="author1" class="50_font_size">
             By First Name Last Name
          </div>
      </div>
        General article text. General article text. General article text.        
      </div>
   </div>

在上面的示例中,我想使用...

require "nokogiri"
document=Nokogiri.HTML(HTML_String)

#Hoping for something like the following:
author_css = node.css_style("author1") 
puts author_css
#=>  {font-family=>"Times New Roman",
#=>   font-weight=> "bold",
#=>   font-size=> 50%} 

如您所见,它应该输出继承的项目,以便我获得元素的正确 CSS。获得此结果的最佳方法是什么?

4

1 回答 1

5

你不能单独用 Nokogiri 来做到这一点。使用CSS_Parser将提供缺失的部分:

require 'nokogiri'
require 'css_parser'
include CssParser

html = <<END_HTML
<head>
  <style type="text/css">
    .myfont {font-family: Times New Roman: font-size: 80% }
    .bold {font-weight: bold}
    .50_font_size { font-size:50% }
  </style>
</head>
<body>
  <div id="article1" class="myfont">
      <div id="title1" class="bold">  
          My Title Text
          <div id="author1" class="50_font_size">
            By First Name Last Name
          </div>
      </div>
        General article text. General article text. General article text.        
      </div>
  </div>
</body>
END_HTML

doc = Nokogiri::HTML(html)
css = doc.at('style').text

parser = CssParser::Parser.new
parser.add_block!(css)

author_div = doc.at('div#author1')
puts parser.find_by_selector('.' + author_div['class'])

哪个输出:

font-size: 50%;

要获得继承的 CSS,您需要从文档顶部开始并深入到所需的节点,确定哪些父节点的设置会影响您的目标节点。

于 2013-01-29T04:32:31.460 回答