2013-07-10 83 views
0

這是在我的rails應用程序的lib/tasks文件夾中,由於某種原因,每次嘗試運行任務時都會收到錯誤。使用rake任務刮掉網站

desc 'Fetch product prices' 
task :fetch_prices => :environment do 

    require "nokogiri" 
    require "open-uri" 

    Product.each do |product| 
    url = "http://www.lowes.ca/search/#{CGI.escape(product.title)}.html" 
    doc = Nokogiri::HTML(open(url)) 
    price = doc.at_css(".fntlb").text[/[0-9\.]+/] 
    product.update_attribute(:price, price) 
    puts "Product #{Product.id} has been updated with price #{price}" 
    end 
end 

以下是我的錯誤,當我嘗試運行此任務: 耙中止! 未定義方法each' for nil:NilClass /vagrant/depot/lib/tasks/product_prices.rake:7:in在'

回答

1

塊中您想要Product.all.each而不是Product.each。雖然這有點奇怪,但錯誤表明它是零。

+0

我把它改成Product.all.each現在出現此錯誤:耙中止! 404 Not Found /vagrant/depot/lib/tasks/product_prices.rake:9:in ' /vagrant/depot/lib/tasks/product_prices.rake:7 :在<頂部(必填)>塊中'' – twillw

+0

賠率是網址無效。在那裏無法真正幫助你。 –

0

您需要定義你的產品變量

更改此:

desc 'Fetch product prices' 
task :fetch_prices => :environment do 

require "nokogiri" 
require "open-uri" 

Product.each do |product| 
    url = "http://www.lowes.ca/search/#{CGI.escape(product.title)}.html" 
    doc = Nokogiri::HTML(open(url)) 
    price = doc.at_css(".fntlb").text[/[0-9\.]+/] 
    product.update_attribute(:price, price) 
    puts "Product #{Product.id} has been updated with price #{price}" 
end 
end 

這樣:

desc 'Fetch product prices' 
task :fetch_prices => :environment do 

require "nokogiri" 
require "open-uri" 

url = "http://www.lowes.ca/search/#{CGI.escape(product.title)}.html" 
doc = Nokogiri::HTML(open(url)) 
product = doc.css('CSS SELECTER FOR YOUR CONTENT') 


Product.each do |product| 
    price = doc.at_css(".fntlb").text[/[0-9\.]+/] 
    product.update_attribute(:price, price) 
    puts "Product #{Product.id} has been updated with price #{price}" 
end 
end