首页 | 新闻 | 新品 | 文库 | 方案 | 视频 | 下载 | 商城 | 开发板 | 数据中心 | 座谈新版 | 培训 | 工具 | 博客 | 论坛 | 百科 | GEC | 活动 | 主题月 | 电子展
返回列表 回复 发帖

在 Linux 上构建 Web spider(4)实例:与股票价格 scraper 通信

在 Linux 上构建 Web spider(4)实例:与股票价格 scraper 通信

例子 2 中用来搜集股票价格的 Web scraper 非常吸引人,不过如果能让这个 scraper 经常性地监视股票价格并在您感兴趣的股票的价格上涨到某个特定值或下跌到某个特定值时就给您发送邮件通知,将更加有用。您不必再等待了。在清单 5 中,将会让这个简单的 Web scraper 能够监视股票并在股票超过预先定义的价格范围时就发送 e-mail 消息。
清单 5. 可以发送 e-mail 警告的股票 scraper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#!/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 脚本有点长,不过它是在  中现有的股票价格搜集脚本基础之上构建的。一个新的函数 getStockQuote 对股票价格搜集功能进行了封装。另外一个函数 sendStockAlert 会向某个 e-mail 地址发送消息(e-mail 地址和发送的消息都可以由用户定义)。主程序只是一个循环,用来获得股票的当前价格,检查价格是否在所限定的范围内,如果不在就发送 e-mail 警告来提醒用户。这里还在检查股票价格时进行了一下延时,原因是不想造成服务器的过载。
清单 6 是一个对一只非常流行的科技股调用这个股票监视程序的例子。每两分钟,这个股票的价格就会被检查并打印出来。当股票超过高位时,就会发送一条 e-mail 消息并会退出脚本。
清单 6. 股票监视脚本的演示
1
2
3
4
5
[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 所示,后面有个到所搜集的数据源的链接。
图 1. 清单 5 中的 Ruby 脚本发送的 E-mail 警告 至此对 scraper 的介绍就告一段落,接下来将深入地了解一下 Web spider 的构建。
返回列表