views:

199

answers:

2

any idea how i can get the code below to produce this output?

1 -
2 - B

i'm getting this error "undefined method `text' for nil:NilClass (NoMethodError)", because i think table 1 does not have the element 'td class=r2' in it.

require 'rubygems'  
require 'nokogiri'  
require 'open-uri'

doc = Nokogiri::HTML.parse(<<-eohtml)
<table class="t1">
    <tbody>
        <tr>
            <td class="r1">1</td>
        </tr>
</tbody>
</table>
<table class="t2">
    <tbody>
        <tr>
            <td class="r1">2</td>
            <td class="r2">B</td>
        </tr>
    </tbody>            
</table>  
eohtml

doc.css('tbody > tr').each do |n|
    r1 = n.at_css(".r1").text
    r2 = n.at_css(".r2").text
    puts "#{r1} - #{r2}"
end
A: 

Don't call the text() method until you've verified you have an element. You can split your call r1 = n.at_css(".r1").text into two lines, or use || (the ruby null coalescing idiom) to set r1 to a default value when the at_css() method returns nil.

JasonTrue
thanks for the suggestion, new at this game :)
A: 

If there are only two tables then your can do the following:

t1_r1 = doc.xpath('//table[@class="t1"]//td[@class="r1"]').text
t1_r2 = doc.xpath('//table[@class="t1"]//td[@class="r2"]').text
t2_r1 = doc.xpath('//table[@class="t2"]//td[@class="r1"]').text
t2_r2 = doc.xpath('//table[@class="t2"]//td[@class="r2"]').text

Let's test result.

>> "#{t1_r1} - #{t1_r2}"
=> "1 - "
>> "#{t2_r1} - #{t2_r2}"
=> "2 - B"
KandadaBoggu