vendredi 8 mai 2015

How do I ignore the nil values in the ruby loop with parsed values from Mechanize?

In my text file are a list of URLs and with Mechanize I'm using that list to parse out the title and meta description. However, some of those URL pages don't have a meta description which stops my script with a nil error.

undefined method `[]' for nil:NilClass (NoMethodError)

I've read up and seen solutions if I were using rails, but for ruby I've only seen .reject and .compact as possible solutions to ignore nil values. I added .compact at the end of the loop, but that doesn't seem to do anything.

require 'rubygems'
require 'mechanize'

File.readlines('parsethis.txt').each do |line|
    page = Mechanize.new.get(line)
    title = page.title
    metadesc = page.at("head meta[name='description']")[:content]
    puts "%s, %s, %s" % [line.chomp, title, metadesc] 
end.compact!

Aucun commentaire:

Enregistrer un commentaire