2007年07月17日

require ‘open-uri’
require ‘CSV’

def fetch_info(code)
  uri = ‘http://finance.sina.com.cn/realstock/company/sh’ + code.to_s + ‘/techchart.shtml?asi’
  open(uri) do |f|
    text = f.read
    title_start = text.index(‘<title>’) + ‘<title>’.size  
    title_end = text.index(‘</title’)
    title = text[title_start...title_end]
    stock_name = title[0...(title.index('_'))]
    rate_start = text.index(‘机构介入比例’) + ‘机构介入比例’.size
    rate_end = rate_start + 4
    rate = text[rate_start...rate_end].to_f
    return [stock_name,rate]
  end
end

def fetch_all_info
  all_info = []
  for code in 600001…600003
    info = fetch_info(code)
    all_info << info
  end
  return all_info
end

def fetch_and_save_all_info
  all_info = fetch_all_info
  CSV.open(‘d:\test\stock.csv’,'w’) do |f|
    for info in all_info
      f << info
    end
  end
end

fetch_and_save_all_info