Pharo
Pharo

Reputation: 45

Undefined method `name' for nil:NilClass (NoMethodError) when running script

When I run the following script to retrieve the first page of google results

#!/usr/bin/env ruby
require 'rubygems'
require 'nokogiri'
require 'open-uri'

  doc = Nokogiri::HTML(open('http://www.google.co.uk/search?q=stackoverflow'))         

  doc.css('div.vsc').each do |element|
    puts element.at_css("h3.r a.l").content
  end

I get a undefined methodcontent' for nil:NilClass (NoMethodError)`

How could I solve that? Or at least how could avoid it showing when executing?

Upvotes: 1

Views: 2126

Answers (1)

undur_gongor
undur_gongor

Reputation: 15954

As Dave Newton already pointed out in his comment, the result of at_css("h3.r a.l") is nil in your case. Neither the NilClass nor the object nil have a method content.

Workaround:

doc.css('div.vsc').each do |element|
  next unless elem = element.at_css("h3.r a.l")
  puts elem.content
end

Upvotes: 1

Related Questions