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

在 Linux 上构建 Web spider(3)实例:搜集股票价格的 scraper

在 Linux 上构建 Web spider(3)实例:搜集股票价格的 scraper

在这个例子中,构建了一个简单的 Web scraper(也称为 屏幕 scraper)来搜集股票价格信息。本例通过使用响应的 Web 页面的模式来强制实现这种功能,代码如下所示:
清单 3. 用来搜集股票价格的简单 Web 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
#!/usr/local/bin/ruby
require 'net/http'

host = "www.smartmoney.com"
link = "/eqsnaps/index.cfm?story=snapshot&symbol="+ARGV[0]

begin

  # 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('<')

  print ARGV[0] + " current stock price " + subset[0..limit-1] +
          " (from stockmoney.com)\n"

end




在这个 Ruby 脚本中,先是打开一个 HTTP 客户机连接到一台服务器上(在本例中是 www.smartmoney.com),并构建一个链接,它会请求获得用户传递进来的某个股票(通过 &symbol=<symbol>)的价格。然后使用 HTTP GET 方法(检索完整的响应页面)来请求这个链接,从中搜索 class="price">,它后面紧接着就是这个股票的当前价格。最后从 Web 页面中截取出这一信息,为用户呈现出来。
要使用股票价格 scraper,只需使用感兴趣的那个股票的符号来调用这个脚本即可,如清单 4 所示。
清单 4. 股票价格 scraper 的示例应用
1
2
3
4
5
6
7
[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]$

返回列表