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 method
content' for nil:NilClass (NoMethodError)`
How could I solve that? Or at least how could avoid it showing when executing?
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
精彩评论