Html 查找指定给元素的CSS样式
获取元素的渲染样式 (还应该能够处理内联CSS) 我一直在学习并理解如何根据ID或类选择节点。但是,我想选择一个节点/元素,并获取分配给它的特定CSS样式,包括继承的样式 CSS样式表:Html 查找指定给元素的CSS样式,html,css,ruby,nokogiri,Html,Css,Ruby,Nokogiri,获取元素的渲染样式 (还应该能够处理内联CSS) 我一直在学习并理解如何根据ID或类选择节点。但是,我想选择一个节点/元素,并获取分配给它的特定CSS样式,包括继承的样式 CSS样式表: <head> <style type="text/css"> .myfont {font-family: Times New Roman: font-size: 80% } .bold {font-weight: bold} .50_font_size { f
<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>
如您所见,它应该输出继承的项,以便获得元素的正确CSS。获得这一结果的最佳方法是什么?你不能单独使用Nokogiri。使用将提供缺少的部件:
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'])
要获得继承的CSS,您需要从文档顶部开始,深入到所需的节点,找出父节点的设置会影响目标节点。好信息-直到现在才知道CSSParser。我真丢脸。谢谢希望有一个类似于javascript的getcomputedstyle()的函数。尝试避免编写脚本来遍历节点,因为我还需要内联CSS,解析内联CSS可能会变得很棘手。我也在考虑使用Watir。Watir可能会这样做。对于您正在做的事情,您需要了解浏览器所知道的一切,这与Ruby、Python或Perl等语言本身所知道的不同。使用Watir或phantomjs,您可以直接运行getcomputedstyle()函数(例如,
Watir\u browser.execute\u脚本(“window.getcomputedstyle(document.getElementById('author1')))
)您可能需要调查像watir webdriver这样的浏览器驱动程序。
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%}
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%;