获取元素的渲染样式 (也应该能够处理内联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。得到这个结果的最佳方法是什么?
答案 0 :(得分: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,您需要从文档的顶部开始并向下钻取到所需的节点,找出父节点的设置将对目标节点产生什么影响。