use*_*677 2 html css ruby nokogiri
获取元素的渲染样式 (也应该能够处理内联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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,我想用...
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%}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,它应该输出继承的项目,以便我获得元素的正确CSS.获得此结果的最佳方法是什么?
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'])
Run Code Online (Sandbox Code Playgroud)
哪个输出:
font-size: 50%;
Run Code Online (Sandbox Code Playgroud)
要获得继承的CSS,您需要从文档的顶部开始并向下钻取到所需的节点,找出父节点的设置将影响您的目标节点.