find first level children in nokogiri rails

Dzmitry picture Dzmitry · Oct 27, 2011 · Viewed 10.8k times · Source

I've faced with a problem how to find first level children from the current element ? For example i have html :

 <table>
   <tr>abc</tr>
   <tr>def</tr>   
   <table>
     <tr>second</tr>
   </table>
 </table>

I am using Nokogiri for rails :

table = page.css('table')
table.css('tr')

It returns all tr inside table. But I need only 2 that first level for the table.

Answer

mu is too short picture mu is too short · Oct 27, 2011

When you say this:

table = page.css('table')

you're grabbing both tables rather than just the top level table. So you can either go back to the document root and use a selector that only matches the rows in the first table as mosch says or you can fix table to be only the outer table with something like this:

table = page.css('table').first
trs   = table.xpath('./tr')

or even this (depending on the HTML's real structure):

table = page.xpath('/html/body/table')
trs   = table.xpath('./tr')

or perhaps one of these for table (thanks Phrogz, again):

table = page.at('table')
table = page.at_css('table')
# or various other CSS and XPath incantations