【问题标题】:Find CSS styles assigned to an element查找分配给元素的 CSS 样式
【发布时间】:2013-01-12 11:31:33
【问题描述】:

获取元素的渲染样式 (应该也可以处理内联 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。获得此结果的最佳方法是什么?

【问题讨论】:

  • 您可能需要调查诸如 watir-webdriver 之类的浏览器驱动程序。

标签: html css ruby nokogiri


【解决方案1】:

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,您需要从文档顶部开始向下钻取到所需的节点,确定哪些父节点的设置会影响您的目标节点。

【讨论】:

  • 好消息 - 直到现在才知道 CSSParser。我真丢脸。谢谢!
  • 希望有一个类似于 javascript 的 getcomputedstyle() 的功能。试图避免编写脚本来遍历节点,因为我还需要内联 CSS 并且解析内联 CSS 可能会变得棘手。我也在考虑使用 Watir。
  • Watir 可能会这样做。对于您正在做的事情,您需要了解浏览器所知道的一切,这与 Ruby、Python 或 Perl 等语言本身所知道的领域/问题不同。
  • 使用 Watir 或 phantomjs,直接运行 getcomputedstyle() 函数(例如watir_browser.execute_script("window.getComputedStyle(document.getElementById('author1'))")
猜你喜欢
  • 2012-07-20
  • 2019-06-05
  • 1970-01-01
  • 2015-04-28
  • 2010-12-13
  • 1970-01-01
  • 1970-01-01
  • 2011-03-16
  • 1970-01-01
相关资源
最近更新 更多