|
在这个 Ruby 脚本中,先是打开一个 HTTP 客户机连接到一台服务器上(在本例中是 www.smartmoney.com),并构建一个链接,它会请求获得用户传递进来的某个股票(通过 &symbol=<symbol>)的价格。然后使用 HTTP GET 方法(检索完整的响应页面)来请求这个链接,从中搜索 class="price">,它后面紧接着就是这个股票的当前价格。最后从 Web 页面中截取出这一信息,为用户呈现出来。
要使用股票价格 scraper,只需使用感兴趣的那个股票的符号来调用这个脚本即可,如清单 4 所示。
清单 4. 股票价格 scraper 的示例应用
[mtj@camus]$ ./stockprice.rb ibm
ibm current stock price 79.28 (from stockmoney.com)
[mtj@camus]$ ./stockprice.rb intl
intl current stock price 21.69 (from stockmoney.com)
[mtj@camus]$ ./stockprice.rb nt
nt current stock price 2.07 (from stockmoney.com)
[mtj@camus]$
|
例子 3:与股票价格 scraper 通信
例子 2 中用来搜集股票价格的 Web scraper 非常吸引人,不过如果能让这个 scraper 经常性地监视股票价格并在您感兴趣的股票的价格上涨到某个特定值或下跌到某个特定值时就给您发送邮件通知,将更加有用。您不必再等待了。在清单 5 中,将会让这个简单的 Web scraper 能够监视股票并在股票超过预先定义的价格范围时就发送 e-mail 消息。
清单 5. 可以发送 e-mail 警告的股票 scraper
#!/usr/local/bin/ruby
require 'net/http'
require 'net/smtp'
#
# Given a web-site and link, return the stock price
#
def getStockQuote(host, link)
# Create a new HTTP connection
httpCon = Net::HTTP.new( host, 80 )
# Perform a HEAD request
resp = httpCon.get( link, nil )
stroffset = resp.body =~ /class="price">/
subset = resp.body.slice(stroffset+14, 10)
limit = subset.index('<')
return subset[0..limit-1].to_f
end
#
# Send a message (msg) to a user.
# Note: assumes the SMTP server is on the same host.
#
def sendStockAlert( user, msg )
lmsg = [ "Subject: Stock Alert\n", "\n", msg ]
Net::SMTP.start('localhost') do |smtp|
smtp.sendmail( lmsg, "rubystockmonitor@localhost.localdomain", [user] )
end
end
#
# Our main program, checks the stock within the price band every two
# minutes, emails and exits if the stock price strays from the band.
#
# Usage: ./monitor_sp.rb <symbol> <high> <low> <email_address>
#
begin
host = "www.smartmoney.com"
link = "/eqsnaps/index.cfm?story=snapshot&symbol="+ARGV[0]
user = ARGV[3]
high = ARGV[1].to_f
low = ARGV[2].to_f
while 1
price = getStockQuote(host, link)
print "current price ", price, "\n"
if (price > high) || (price < low) then
if (price > high) then
msg = "Stock "+ARGV[0]+" has exceeded the price of "+high.to_s+
"\n"+host+link+"\n"
end
if (price < low) then
msg = "Stock "+ARGV[0]+" has fallen below the price of "+low.to_s+
"\n"+host+link+"\n"
end
sendStockAlert( user, msg )
exit
end
sleep 120
end
end
|
这个 Ruby 脚本有点长,不过它是在 清单 3 中现有的股票价格搜集脚本基础之上构建的。一个新的函数 getStockQuote 对股票价格搜集功能进行了封装。另外一个函数 sendStockAlert 会向某个 e-mail 地址发送消息(e-mail 地址和发送的消息都可以由用户定义)。主程序只是一个循环,用来获得股票的当前价格,检查价格是否在所限定的范围内,如果不在就发送 e-mail 警告来提醒用户。这里还在检查股票价格时进行了一下延时,原因是不想造成服务器的过载。
清单 6 是一个对一只非常流行的科技股调用这个股票监视程序的例子。每两分钟,这个股票的价格就会被检查并打印出来。当股票超过高位时,就会发送一条 e-mail 消息并会退出脚本。 清单 6. 股票监视脚本的演示
[mtj@camus]$ ./monitor_sp.rb ibm 83.00 75.00 mtj@mtjones.com
current price 82.06
current price 82.32
current price 82.75
current price 83.36
|
所生成的 e-mail 如图 1 所示,后面有个到所搜集的数据源的链接。
共6页: 上一页 [1] [2] 3 [4] [5] [6] 下一页
|