2013-07-10 84 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