How to get Nokogiri to ignore HTML elements that doesn't exist

Posted by user296507 on Stack Overflow See other posts from Stack Overflow or by user296507
Published on 2010-03-19T02:07:36Z Indexed on 2010/03/19 2:11 UTC
Read the original article Hit count: 268

Filed under:
|
|
|

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

© Stack Overflow or respective owner

Related posts about ruby

Related posts about nokogiri