Yahoo! WebサービスAPIサンプル

概要


Yahoo!WebサービスAPIのWeb検索のサンプルです。
YahooのWebサービスAPIを利用するにはIDが必要です。以下のサイトからIDを取得することができます。
(Yahoo!IDを事前に取得していること。無料)
http://developer.yahoo.co.jp/search/

サンプルページ


指定されたキーワードで検索結果を取得し、タイトル、URL、サマリーを表示します。
http://sakura-computer.co.jp/webservice/yahoo/webs...

参考文献・リンク


CGIライブラリのリファレンスマニュアル
REXMLについて(日本語リファレンスマニュアル)

ソースコード


#!/usr/local/bin/ruby

require "cgi"
require "open-uri"
require "rexml/document"

begin
  cgi = CGI.new('html4Tr')
  html = "キーワード「" + cgi["query"] + "」に一致する情報は見つかりませんでした。"
  credit = "<!-- Begin Yahoo! JAPAN Web Services Attribution Snippet -->
<a href='http://developer.yahoo.co.jp/about'><img ^src='http://i.yimg.jp/images/yjdn/yjdn_attbtn1_125_17.gif' title='Webサービス by Yahoo! JAPAN' alt='Web ^Services by Yahoo! JAPAN' width='125' height='17' border='0' style='margin:15px 15px 15px 15px'></a>
<!-- End Yahoo! JAPAN Web Services Attribution Snippet -->"

  #キーワードが入力されているときのみ検索処理を行う。
  if cgi["query"] != "" then
    
    query = "http://api.search.yahoo.co.jp/WebSearchService/V1/webSearch?appid=取得したアプリケーションID&query=" + CGI.escape(cgi["query"])
    xml = REXML::Document.new(open(query))
    
    #検索結果を確認し、結果HTMLを作成する。
    if xml.elements["ResultSet"].attributes["totalResultsReturned"] != 0 then
      html = ""
      xml.elements.each("ResultSet/Result") { |line|
        html += "<a href='" + line.elements["ClickUrl"].text + "'>" + line.elements["Title"].text + "</a><br/>" +
        "<blockquote>" + line.elements["Summary"].text + "</blockquote>"
      }
    end
  end

  #ページの作成
  title = "Yahoo!検索APIサンプル " + cgi["query"]
  cgi.out do
    cgi.html do
      cgi.head { cgi.title { title } } + cgi.body do
        cgi.h3 { "Yahoo!WebサービスAPIサンプル(Web検索)" } + 
          "検索キーワードを入力してボタンをクリックしてください。" +
          cgi.form do
          cgi.text_field("query", cgi["query"]) +
            cgi.br +
            cgi.submit
        end +
          cgi.h3 { "検索結果(10件)" } + html + cgi.br + credit
      end
    end
  end
  
#例外処理
rescue => ex
  cgi.out do
    cgi.html do
      cgi.head { cgi.title { title } } + cgi.body do
        "例外が発生しました。" + cgi.br +
        ex.message + cgi.br +
        (ex.backtrace.collect { |trace|
          trace + cgi.br
         }).join(" ") + cgi.br +
          cgi.pre { xml }
      end
    end
  end
end
2008年02月21日(木) 20:31:43 Modified by y_tabira




スマートフォン版で見る