开发者

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

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>  
e开发者_开发知识库ohtml

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


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"


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜