From: Robert Klemme Date: 2010-10-20T16:47:35+09:00 Subject: Re: Help missing something BASIC On Wed, Oct 20, 2010 at 3:40 AM, Don Norcott wrote: > This code is conceptually what I want to do with the nokogiri code below > s1 = [1,2,3] ; s2 = [4,5,6]; s3 = [7,8,9] > str = [s1,s2,s3] > str.each do |itm| >  puts "********" >  puts " #{itm[2]}" Select middle item from each s1 , s2 ,s3 >  puts "*********" > end > Results as expected > ******** >  3 > ********* > ******** >  6 > ********* > ******** >  9 > ********* > > I have an html page with multiple ...
elements > (equivalent to str above) and want to process each table (equivalent to > s1, s2, s3) and extract one item page > doc.xpath("//table[@class='result']").each do |node|   # select a table >  puts "*************" >  puts node.to_html        # as expected >   puts node.xpath("//td[@class='itemNumbr']")  # 15 per each >  puts "*************" > end > ---------------------- NOKOGIRI CODE ---------------------- > > The output below dispays the table HTML as expected - but not itemnumbrs > *********** > for item 1 >
2....../td> > ...... > 1....../td> > 15....../td> > ********** > ********** > for item 3 >
15 tables but the output indicates otherwise.  I think node should > always contain HTML for a single table only, but I appear to be wrong. > > Also if i put a subscript on the first xpath > doc.xpath("//table[@class='result'][5]").each do |node| > to ensure only one table is found, still get itemnumbrs for all 15 table > elements > > WHAT AM I MISSING HERE Please do not shout. You are probably missing how XPath works. With the queries given by you above you will always get *all* td nodes with class "itemNumbr" in the document. You need a two level approach using *relative* queries: irb(main):004:0> html = "" << (1..3).map {|i| "
#{i}
"}.join(" ") << "" => "
1
2
3
" irb(main):005:0> doc = Nokogiri.parse html => #]>]>, #, #]>]>, #, #]>]>]>]> irb(main):006:0> doc.xpath '//td' => [#]>, #]>, #]>] irb(main):007:0> doc.xpath('//table').each do |tab| irb(main):008:1* p tab, tab.xpath('td') # relative! irb(main):009:1> puts '----' irb(main):010:1> end #]>]> [#]>] ---- #]>]> [#]>] ---- #]>]> [#]>] ---- => 0 Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/