在Ruby中使用Nokogiri解析HTML

Ozi*_*Maq 6 ruby xpath nokogiri

使用此HTML代码:

<div class="one">
  .....
</div>
<div class="one">
  .....
</div>
<div class="one">
  .....
</div>
<div class="one">
  .....
</div>
Run Code Online (Sandbox Code Playgroud)

我如何选择Nokogiri的第二或第三个div,其类是一个?

Phr*_*ogz 7

您可以使用Ruby来削减特定项目的大型结果集:

page.css('div.one')[1,2]  # Two items starting at index 1 (2nd item)
page.css('div.one')[1..2] # Items with indices between 1 and 2, inclusive
Run Code Online (Sandbox Code Playgroud)

因为Ruby索引从零开始,所以您必须注意所需的项目.

或者,您可以使用CSS选择器查找第n个项目:

# Second and third items from the set, jQuery-style
page.css('div.one:eq(2),div.one:eq(3)')

# Second and third children, CSS3-style
page.css('div.one:nth-child(2),div.one:nth-child(3)')
Run Code Online (Sandbox Code Playgroud)

或者您可以使用XPath来获取特定匹配项:

# Second and third children
page.xpath("//div[@class='one'][position()=2 or position()=3]")

# Second and third items in the result set
page.xpath("(//div[@class='one'])[position()=2 or position()=3]")
Run Code Online (Sandbox Code Playgroud)

使用CSS和XPath备选方案时请注意:

  1. 编号从1开始,而不是0
  2. 您可以使用at_cssat_xpath不是返回第一个匹配元素,而不是NodeSet.

    # A NodeSet with a single element in it:
    page.css('div.one:eq(2)')
    
    # The second div element
    page.at_css('div.one:eq(2)')
    
    Run Code Online (Sandbox Code Playgroud)

最后,请注意,如果您使用XPath按索引选择单个元素,则可以使用更短的格式:

# First div.one seen that is the second child of its parent
page.at_xpath('//div[@class="one"][2]')

# Second div.one in the entire document
page.at_xpath('(//div[@class="one"])[2]')
Run Code Online (Sandbox Code Playgroud)


Ism*_*reu 5

page.css('div.one')[1] # For the second
page.css('div.one')[2] # For the third
Run Code Online (Sandbox Code Playgroud)

  • 最初这个答案有CSS`div#one`.找到一个*id*为"one"的div,但HTML有*class*的`one`.这就是我制作CSS`div.one`的原因.```选择一个ID,`.`选择一个类. (2认同)