Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find first level children in nokogiri rails

Tags:

ruby

nokogiri

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.

like image 298
Dzmitry Avatar asked Oct 27 '11 18:10

Dzmitry


2 Answers

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
like image 82
mu is too short Avatar answered Sep 23 '22 23:09

mu is too short


You can do

rows = page.css('body > table > tr')

Perhaps you have to adapt the selector to your container element (i chose 'body' here)

like image 40
moritz Avatar answered Sep 25 '22 23:09

moritz