【问题标题】:Select all classes after the first of its type选择第一个类之后的所有类
【发布时间】:2014-09-09 15:11:43
【问题描述】:

如果我有以下 HTML 结构

<section class="main-gallery homeowner-rating content-block">
  <!--content-->
</section>

<section class="homeowner-rating content-block">
  <!--content-->
</section>

<section class="homeowner-rating content-block">
  <!--content-->
</section>

<section class="homeowner-rating content-block">
  <!--content-->
</section>

如何选择除第一个之外的所有homeowner-rating.content-block 类?

为了提供一些上下文,我使用 Nokogiri 设置了一个简单的屏幕抓取,但它试图从返回空白结果的第一部分类中获取信息。

def get_testimonials
  url = 'http://www.ratedpeople.com/profile/lcc-building-and-construction'
  doc = Nokogiri::HTML.parse(open url)
  testimonial_section = doc.css('.homeowner-rating.content-block').each do |t|
    title = t.css('h4').text.strip
    comments = t.css('q').text.strip
    author = t.css('cite').text.strip
  end
 end

【问题讨论】:

    标签: css ruby-on-rails ruby nokogiri


    【解决方案1】:

    根据您当前的设置,有多种方法:

    .homeowner-rating+.homeowner-rating
    {
       color: red;  
    }
    

    演示:http://jsfiddle.net/PKEv5/

    .homeowner-rating:not(.main-gallery)
    {
       color: red;  
    }
    

    演示:http://jsfiddle.net/PKEv5/1/

    这只有在主库是节点的第一个子节点时才有效:

    .homeowner-rating:not(:first-child)
    {
       color: red;  
    }
    

    演示:http://jsfiddle.net/PKEv5/2/

    【讨论】:

    • 非常感谢,我可以通过两个选项,所以 not(.main-gallery) 和 not(:last-child) ?
    • 绝对是,.homeowner-rating:not(.main-gallery):not(:last-child) jsfiddle.net/PKEv5/3
    • 啊是的,你可以,我可以把它们锁起来
    【解决方案2】:

    使用 Nokogiri 很简单:

    require 'nokogiri'
    
    doc = Nokogiri::HTML::DocumentFragment.parse(<<EOT)
    <section class="main-gallery homeowner-rating content-block">
      <p>1</p>
    </section>
    
    <section class="homeowner-rating content-block">
      <p>2</p>
    </section>
    
    <section class="homeowner-rating content-block">
      <p>3</p>
    </section>
    
    <section class="homeowner-rating content-block">
      <p>4</p>
    </section>
    EOT
    
    doc.css('.homeowner-rating')[1..-1].map(&:to_html)
    # => ["<section class=\"homeowner-rating content-block\">\n  <p>2</p>\n</section>",
    #     "<section class=\"homeowner-rating content-block\">\n  <p>3</p>\n</section>",
    #     "<section class=\"homeowner-rating content-block\">\n  <p>4</p>\n</section>"]
    

    Nokogiri 的 searchcssxpath 方法返回 NodeSet,其行为类似于数组,因此您可以对结果进行切片以获取块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-22
      • 1970-01-01
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多