Ruby刮刀。如何导出到CSV?

时间:2012-05-21 02:59:20

标签: ruby fastercsv scraper anemone

我写了这个ruby脚本来从制造商网站上抓取产品信息。在数组中抓取和存储产品对象有效,但我无法弄清楚如何将数组数据导出到csv文件。抛出此错误: scraper.rb:45:主要的未定义方法`send_data':对象(NoMethodError)

我不明白这段代码。这是做什么的,为什么它不能正常工作?

  send_data csv_data, 
            :type => 'text/csv; charset=iso-8859-1; header=present', 
            :disposition => "attachment; filename=products.csv" 

完整代码:

#!/usr/bin/ruby

require 'rubygems'
require 'anemone'
require 'fastercsv'

productsArray = Array.new

class Product
    attr_accessor :name, :sku, :desc
end

# Scraper Code

Anemone.crawl("http://retail.pelicanbayltd.com/") do |anemone|
    anemone.on_every_page do |page|

        currentPage = Product.new

        #Product info parsing
        currentPage.name = page.doc.css(".page_headers").text
        currentPage.sku = page.doc.css("tr:nth-child(2) strong").text
        currentPage.desc = page.doc.css("tr:nth-child(4) .item").text

        if currentPage.sku =~ /#\d\d\d\d/
            currentPage.sku = currentPage.sku[1..-1]
            productsArray.push(currentPage)
        end
    end
end

# CSV Export Code

products = productsArray.find(:all) 
csv_data = FasterCSV.generate do |csv| 
    # header row 
    csv << ["sku", "name", "desc"] 

    # data rows 
    productsArray.each do |product| 
      csv << [product.sku, product.name, product.desc] 
    end 
  end 

  send_data csv_data, 
            :type => 'text/csv; charset=iso-8859-1; header=present', 
            :disposition => "attachment; filename=products.csv" 

3 个答案:

答案 0 :(得分:1)

如果您是Ruby的新手,您应该使用Ruby 1.9或更高版本,在这种情况下,您可以使用内置的CSV输出,该输出构建在快速csv和l18n支持中:

require 'csv'
CSV.open('filename.csv', 'w') do |csv|
  csv << [sku, name, desc]
end

http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html

答案 1 :(得分:0)

File.open('filename.csv', 'w') do |f|
  f.write(csv_data)
end

答案 2 :(得分:0)

这样做可能更有意义:

@csv = FasterCSV.open('filename.csv', 'w')

然后随着时间写下来:

@csv << [sku, name, desc]

这样,如果你的脚本在中途崩溃,你至少得到了一半的数据。