Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | YahooファイナンスをWebスクレイピングしてUSD/JPYのレートを取得

概要

YahooファイナンスをWebスクレイピングしてUSD/JPYのレートを取得

内容

YahooファイナンスをWebスクレイピングしてUSD/JPYのレートを取得します。
また、取得結果と標準入力に指定した数値を掛け合わせてドル価格から円価格への変換をします。

仕様

・引数は1つ
・引数は数値
・YahooファイナンスのURL、htmlのタグや属性が変更になったらこのスクリプトは動作しなくなる

サンプルコード

# encoding: utf-8
require "open-uri"
require "nokogiri"
require_relative "standard_io"

class YenDollar
  include StandardIo
  validate_args_counts 1
  validate_us_dollar 0

  def yd_rate
    uri = "http://stocks.finance.yahoo.co.jp/stocks/detail?code=USDJPY=X"
    page = URI.parse(uri).read

    document = Nokogiri::HTML(page, uri)
    document.xpath('//td[@class="stoksPrice"]').text
  end
end

yen_dollar = YenDollar.new
exit unless yen_dollar.validate
dollar = $*[0].to_f
rate = yen_dollar.yd_rate.to_f
print "$#{dollar} × #{rate}(USD/JPY)="
puts "\\#{(rate * dollar).to_i.to_s}"

standard_io

standard_io部に関しては下記記事参照
Ruby | 標準入出力処理時のValidationをクラスマクロで共通化
http://d.hatena.ne.jp/tbpg/20130625/1372165415

補足

nokogiriをインストールしていない人はgem installすること

出力

$ ruby yen-dollar.rb 64
$64 × 97.77(USD/JPY)=\6257