用rake任务刮网站

时间:2013-07-10 18:35:58

标签: ruby-on-rails ruby nokogiri

这是我的rails应用程序中的lib / tasks文件夹,由于某些原因,每次尝试运行任务时都会出现错误。

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阻止

2 个答案:

答案 0 :(得分:1)

您希望Product.all.each不是Product.each。虽然它有点奇怪,但错误表明它是零。

答案 1 :(得分: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