Reputation: 198
I am using Nokogiri to scrape data from a HTML document, but I'm running into the following error:
`block in <main>': undefined method `[]' for nil:NilClass (NoMethodError)
This is the code to reproduce the problem:
require 'rubygems'
require 'nokogiri'
require 'open-uri'
url = "http://www.somewebsite.com/somepage/some"
doc = Nokogiri::HTML(open(url))
puts doc.at_css("title").text
doc.css(".Info_listing").each do |x|
puts x.at_css(".MoreInfo")[:href]
end
Does anyone know why I'm getting this error?
Upvotes: -2
Views: 469
Reputation: 369394
at_css
will return nil
if there's no matching element.
If you want to get MoreInfo
class element inside Info_listing
-class element, you'd better to use following code:
doc.css(".Info_listing .MoreInfo").each do |x|
puts x[:href]
end
Upvotes: 2