【问题标题】:nokogiri excluded elements from select all by classnokogiri 按类从全选中排除元素
【发布时间】:2011-08-18 05:53:29
【问题描述】:

我只是想从一个节点的所有子节点的选择中按类排除几个子元素

page.css('div.parent > *').each do |child|
  if (child["class"].content != 'this' && child["class"].content != 'that')
    array.push(child.text.to_s)
  end
end 

我知道这不是写语法,但一直无法找到如何选择元素类,而不是选择和元素 by 类。

【问题讨论】:

    标签: ruby nokogiri


    【解决方案1】:

    css 方法为您提供Nokogiri::XML::Element 实例,这些实例的大部分行为来自其Nokogiri::XML::Node 父类。要从节点中获取属性,请使用[]

    page.css('div.parent > *').each do |child|
      if(!%w{this that}.include?(child['class']))
        array.push(child.text.to_s)
      end
    end
    

    如果这对您更有意义,您也可以使用 if(child['class'] != 'this' && child['class'] != 'that')

    但是,class 属性可以有多个值,因此您可能希望在空白处将它们拆分为多个部分:

    exclude = %w{this that}
    page.css('div.parent > *').each do |child|
      classes = (child['class'] || '').split(/\s+/)
      if((classes & exclude).length > 0)
        array.push(child.text.to_s)
      end
    end
    

    intersection 只是查看两个数组是否有任何共同元素的简单方法(即classes 包含您想要排除的任何元素)。

    【讨论】:

    • 谢谢 mu,这就是我所追求的。你忘了关闭第二行的if
    • @Aaron:谢谢,添加了缺少的括号。
    • 啊,感谢第二个块,这可能更健壮一些。
    猜你喜欢
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2020-10-26
    • 2014-08-19
    • 2012-10-24
    • 2016-02-21
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多