Search code examples
rubynokogiri

find first level children in nokogiri rails


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.


Solution

  • 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