今天打开github,发现Ruby的spreadsheet包竟然年久失修,不支持xlsx格式。
综合比较了下,发现fast_excel包比creek包还是好用。
沪深A股数据依然源自东方财富网。
fast_excel包比原生的win32ole包速度快了几倍。
代码如下所示:
# -*- coding: UTF-8 -*-
require "url"
require "json"
require "fast_excel"
begin
abc = URL.new("http://73.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=20&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152")
sum = abc.get.json["data"]["total"].to_s
url = URL.new("http://73.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=#{sum}&po=1&np=1&ut=bd1d9ddb04089700cf9c27f6f7426281&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152")
filename = "hushenAstock" + Time.now.strftime("%Y%m%d%H%M%S") + ".xlsx"
data = url.get.json["data"]["diff"]
workbook = FastExcel.open("#{filename}", constant_memory: true)
worksheet = workbook.add_worksheet("沪深A股")
worksheet.append_row(["股票名称", "股票代码", "最新价", "跌涨幅", "跌涨额", "成交量", "成交额", "振幅", "换手率", "市盈率", "量比", "最高", "最低", "今开", "昨收", "市净率"])
for i in 2..data.length+1
worksheet.append_row([data[i-2]["f14"], "=TEXT(#{data[i-2]["f12"]},\"000000\")", data[i-2]["f2"], data[i-2]["f3"] == "-" ? data[i-2]["f3"] : data[i-2]["f3"].to_s + "%", data[i-2]["f4"], data[i-2]["f5"], data[i-2]["f6"], data[i-2]["f7"] == "-" ? data[i-2]["f7"] : data[i-2]["f7"].to_s + "%", data[i-2]["f8"] == "-" ? data[i-2]["f8"] : data[i-2]["f8"].to_s + "%", data[i-2]["f9"], data[i-2]["f10"], data[i-2]["f15"], data[i-2]["f16"], data[i-2]["f17"], data[i-2]["f18"], data[i-2]["f23"]])
end
workbook.close
rescue Exception => e
puts e.message
puts e.backtrace.inspect
ensure
puts "Program end!"
end
结果如下链接文章所示:
Ruby抓取沪深A股数据