如何访问样式div内的跨度?

时间:2013-11-13 20:22:51

标签: html css ruby nokogiri

我有这样的HTML:

<div style = 'display: hidden'>
<span class = "thing">text</span>
</div>

<div style = 'display: block'>
<span class = "thing">text</span>
</div>

<div style = 'display: hidden'>
<span class = "thing">text</span>
</div>

我想只选择带有“thing”类的<span>标签,它出现在unhidden div中。我怎么能用Nokogiri宝石做到这一点?

这就是我正在尝试的:

page = Nokogiri::HTML(open(@url))
item_list = page.css("div[@style != 'display: hidden'] span.thing")

1 个答案:

答案 0 :(得分:1)

以下是我要做的事情:

require 'nokogiri'

doc = Nokogiri::HTML.parse <<-eotl
<div style = 'display: hidden'> <span class = "thing">text1</span> </div>
<div style = 'display: block'> <span class = "thing">text2</span> </div>
<div style = 'display: hidden'> <span class = "thing">text3</span> </div>
<div style = 'display: foo'> <span class = "thing">text4</span> </div>
eotl

doc.css("div:not([style$=hidden])>span.thing").size # => 2

doc.css("div:not([style$=hidden])>span.thing").each do |tag|
  p [tag.name,tag.text]
end
# >> ["span", "text2"]
# >> ["span", "text4"]

其他两个主要的CSS选择器,我想向您介绍,如下所示:

:not

  

选择与给定选择器不匹配的所有元素。

[attribute$=value]

  

选择具有指定属性的元素,其值完全以给定字符串结尾。比较区分大小写。