1

我有这样的 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>

我只想选择<span>出现在未隐藏 div 中的“事物”类的标签。我怎样才能用 Nokogiri 宝石做到这一点?

这就是我正在尝试的:

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

1 回答 1

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]

选择具有指定属性且值恰好以给定字符串结尾的元素。比较区分大小写。

于 2013-11-13T20:29:47.027 回答