如何从URL列表中抓取数据并使用nokogiri将数据保存到CSV

时间:2012-10-31 20:06:26

标签: ruby csv nokogiri

我有一个名为bontyurls.csv的文件,如下所示:

http://bontrager.com/model/11383
http://bontrager.com/model/01740
http://bontrager.com/model/09595

我希望我的脚本读取该文件,然后吐出一个这样的文件:bonty_test_urls_results.csv

url,model_names
http://bontrager.com/model/11383,"Road TLR Conversion Kit"
http://bontrager.com/model/01740,"404 File Not Found"
http://bontrager.com/model/09595,"RXL Road"

这是我到目前为止所得到的:

# based on code from here: http://www.andrewsturges.com/2011/09/how-to-harvest-web-data-using-ruby-and.html

require 'nokogiri'
require 'open-uri'
require 'csv'

@urls = Array.new
@model_names = Array.new

urls = CSV.read("bontyurls.csv")
(0..urls.length - 1).each do |index|
  puts urls[index][0]
  doc = Nokogiri::HTML(open(urls[index][0]))
  doc.xpath('//h1').each do |model_name|
    @model_name << model_name.content
  end
end

# write results to file  
CSV.open("bonty_test_urls_results.csv", "wb") do |row|
  row << ["url", "model_names"]
  (0..@urls.length - 1).each do |index|
    row << [
      @urls[index], 
      @model_names[index]]
  end
end

该代码无效。我收到了这个错误:

$ ruby bonty_test_urls.rb 
http://bontrager.com/model/00310
bonty_test_urls.rb:15:in `block (2 levels) in <main>': undefined method `<<' for nil:NilClass (NoMethodError)
    from /home/simon/.rvm/gems/ruby-1.9.3-p194/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:239:in `block in each'
    from /home/simon/.rvm/gems/ruby-1.9.3-p194/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `upto'
    from /home/simon/.rvm/gems/ruby-1.9.3-p194/gems/nokogiri-1.5.5/lib/nokogiri/xml/node_set.rb:238:in `each'
    from bonty_test_urls.rb:14:in `block in <main>'
    from bonty_test_urls.rb:11:in `each'
    from bonty_test_urls.rb:11:in `<main>'

以下是一些至少返回model_name的代码。我只是无法让它在更大的脚本中工作:

require 'open-uri'
require 'nokogiri'

doc = Nokogiri::HTML(open("http://bontrager.com/model/09124"))
doc.xpath('//h1').each do |node|
  puts node.text
end

另外,我还没想出如何处理返回404的网址。

2 个答案:

答案 0 :(得分:2)

我就是这样做的:

require 'csv'
require 'nokogiri'
require 'open-uri'

CSV_OPTIONS = {
  :write_headers => true,
  :headers => %w[url model_names]
}

CSV.open('bonty_test_urls_results.csv', 'wb', CSV_OPTIONS) do |csv|
  csv_doc = File.foreach('bontyurls.csv') do |url|
    url.chomp!
    begin
      doc = Nokogiri.HTML(open(url))
      h1 = doc.at('h1').text.strip
      h1 = doc.at('title').text.strip.sub(/^Bontrager: /i, '') if (h1.empty?)
      csv << [url, h1]
    rescue OpenURI::HTTPError => e
      csv << [url, e.message]
    end
  end
end

生成CSV文件,如:

url,model_names
http://bontrager.com/model/11383,Road TLR Conversion Kit (Model #11383)
http://bontrager.com/model/01740,404 File Not Found
http://bontrager.com/model/09595,RXL Road (Model #09595)

答案 1 :(得分:0)

你声明@model_names,但是尝试推入@model_name,这就是为什么它没有。