解析HTML与引入nokogiri在Ruby中
问题描述:
有了这个HTML代码:解析HTML与引入nokogiri在Ruby中
<div class="one">
.....
</div>
<div class="one">
.....
</div>
<div class="one">
.....
</div>
<div class="one">
.....
</div>
如何与引入nokogiri选择第二或第三格,它的类呢?
答
page.css('div.one')[1] # For the second
page.css('div.one')[2] # For the third
答
您可以使用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
由于Ruby索引从零开始,你必须与你的项目需要照顾。
或者,您可以使用CSS选择器找到nth item:
# 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)')
或者您可以使用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]")
同时与CSS和XPath的选择注意:
- 编号从1开始,而不是0
-
您可以使用
at_css
和at_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)')
最后,请注意,如果您选择用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]')
+0
非常感谢你提供了大量的例子。我们需要更多这样的答案! +1 – 2016-03-10 19:18:52
本来这个答案有CSS'DIV#one' 。这找到了一个* id为'one'的div,但是HTML有'one'的* classes *。这就是为什么我制作了CSS'div.one'。 '#'选择一个ID,'.'选择一个类。 – 2012-04-22 23:24:29