用Ruby中的Nokogiri解析HTML
使用此HTML代码:用Ruby中的Nokogiri解析HTML,ruby,xpath,nokogiri,Ruby,Xpath,Nokogiri,使用此HTML代码: ..... ..... ..... ..... 如何使用Nokogiri选择第二个或第三个类为1的div?page.css('div.one')[1]#第二个类为 page.css('div.one')[2]#第三页 您可以使用Ruby将大型结果集缩减到特定项: page.css('div.one')[1,2] # Two items starting at index 1 (2nd item) page.css('div.one')[1..2] # Items wi
.....
.....
.....
.....
如何使用Nokogiri选择第二个或第三个类为1的div?page.css('div.one')[1]#第二个类为
page.css('div.one')[2]#第三页
您可以使用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选择器查找:
或者,您可以使用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备选方案,请注意:
at_css
和at_xpath
取回第一个这样的匹配元素,而不是节点集
# 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)')
# 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]')
最初这个答案是CSS
div#one
。它查找id为one
的div,但HTML的类为one
。这就是我制作CSSdiv.one
的原因#
选择一个ID,
选择一个类。非常感谢您提供了大量的示例。我们需要更多这样的答案+1.
# 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]')