Google AJAX Search APIを触ってみる

Custom Search  |  Google Developersを適当に読みながら使い方を調べてみる.

とりあえず適当にhttp://www.google.com/uds/samples/apidocs/raw-searchers.htmlソースコードを読んで,実際に遊んでみた.

  • このソースが一番弄れそうだったので選んだ.
  • 他のサンプルコードはほとんどgoogle側が提供してくれているインタフェースをちょちょいと弄って使う程度のものだった…ブログとかの設定程度?のことしかできなかったので選んだ.
  • できればGoogleで検索した結果のXML(DOM木)を直接弄りたかったので選んだ.

DOM

このプログラムでは,googleに投げたクエリの結果を一つずつDivという変数にHtmlDivElementオブジェクトの形で格納する.(本プログラムでは4つの検索結果が返ってくる)
このHtmlDivElementの中身は適当に解析した結果

これは”aa”という検索をGoogleに投げて帰ってきたDivの中身を分かりやすいように整理してみたもの
<DIV>
  <DIV>
    <text>アメリカン航空(AA)</text>
    <innerHTML><A href="http://www.americanairlines.jp/" class="gs-title" target="_blank">アメリカン航空(<B>AA</B>)</A></innerHTML>
  </DIV>
  <DIV>
    <text>AAmusement ParkでAAを楽しもう! ... ウーマンズ・サイト「AA Style」では、女性  だけの特典が満載!航空券などのプレゼントも当たる! ... Copyright 2007 American   Airlines,Inc. All Rights Reserved.</text>
    <innerHTML>AAmusement Parkで<B>AA</B>を楽しもう! <B>...</B> ウーマンズ・サイト「<B>AA</B> Style」では、女性  だけの特典が満載!航空券などのプレゼントも当たる! <B>...</B> Copyright 2007 <B>American</B>   <B>Airlines</B>,Inc. All Rights Reserved.</innerHTML>
  </DIV>
  <DIV>
    <text>www.americanairlines.jp</text>
    <innerHTML>www.americanairlines.jp</innerHTML>
  </DIV>
  <DIV>
    <text>www.americanairlines.jp/</text>
    <innerHTML>www.americanairlines.jp/</innerHTML>
  </DIV>
  <DIV>
    <text>Google からクリップ - 11/2007</text>
    <innerHTML><A href="http://code.google.com/apis/ajaxsearch/faq.html" class="gs-watermark" target="_blank">Google からクリップ - 11/2007</A></innerHTML>
  </DIV>
</DIV>

という形になっているくさい.
分かりやすいように,必要最低限の機能だけ残したサンプルを作りました→Raw Searchers - Google AJAX Search API demo(一番下にソースも晒します)
上述したXMLを表示してくれているくさいことが良く分かります.

    while (counter < div.childNodes.length) {
      div.childNodes.item(counter).text;
      div.childNodes.item(counter).tagName;
      div.childNodes.item(counter).innerHTML;
      counter++; 
    }

こんな感じでアクセスできます.

Google AJAX Search APIを使ってみる.

まずhttp://code.google.com/apis/ajaxsearch/signup.htmlに行って,AJAX Search API Keyというものを取得してください.

  • I have read and agree with the terms and conditionsにチェックをつけて
  • My web site URL:のボックスに適当なURLを入力します(http://localhost/でもhttp://127.0.0.1/でもいいようです)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Raw Searchers - Google AJAX Search API demo</title>
    
    <script src="http://www.google.com/uds/api?file=uds.js&amp;v=0.1&amp;key=自分のキー" type="text/javascript"></script>
    <script type="text/javascript">


    function OnLoad() {
      new RawSearchControl();
    }

    function RawSearchControl() {
      this.searcherform = document.getElementById("searcher");
      this.results = document.getElementById("results");
      this.searchform = document.getElementById("searchform");

      // create map of searchers as well as note the active searcher
      this.activeSearcher = "web";
      this.searchers = new Array();

      // wire up a raw GwebSearch searcher
      var searcher = new GwebSearch();
      searcher.setNoHtmlGeneration();
      searcher.setSearchCompleteCallback(this,
                                         RawSearchControl.prototype.searchComplete,
                                         [searcher]
                                         );
      this.searchers["web"] = searcher;

      // now, create a search form and wire up a submit and clear handler
      this.searchForm = new GSearchForm(true, this.searchform);
      this.searchForm.setOnSubmitCallback(this,
                                          RawSearchControl.prototype.onSubmit);
      this.searchForm.setOnClearCallback(this,
                                          RawSearchControl.prototype.onClear);
    }

    /////////////検索終了後…/////////////
    RawSearchControl.prototype.computeActiveSearcher = function() {
      this.activeSearcher = "web";
      return;
    }
    /////////検索ボタンが押されたら…/////////
    RawSearchControl.prototype.onSubmit = function(form) {
      this.computeActiveSearcher();
      if (form.input.value) {
        this.searchers[this.activeSearcher].execute(form.input.value);
      }
      return false;
    }

    RawSearchControl.prototype.onClear = function(form) {
      this.clearResults();
    }
    
    /////////検索が成功したら…////////
    RawSearchControl.prototype.searchComplete = function(searcher) {
      this.clearResults();// always clear old from the page
      if (searcher.results && searcher.results.length > 0) {// if the searcher has results then process them

        //////HTMLを取得する//////
        var div = createDiv("Result Html", "header");
        //this.results.appendChild(div);
        for (var i=0; i<searcher.results.length; i++) {
          var result = searcher.results[i];
          searcher.createResultHtml(result);
          if (result.html) {
            div = result.html.cloneNode(true);
          } else {
            div = createDiv("** failure to create html **");
          }
          this.results.appendChild(div);//resultsに突っ込む
        }
      }
    }

    RawSearchControl.prototype.clearResults = function() {
      removeChildren(this.results);
    }

    //Static DOM Helper Functions
    function removeChildren(parent) {
      while (parent.firstChild) {
        parent.removeChild(parent.firstChild);
      }
    }
    function createDiv(opt_text, opt_className) {
      var el = document.createElement("div");
      if (opt_text) {
        el.innerHTML = opt_text;
      }
      if (opt_className) { el.className = opt_className; }
      return el;
    }

    GSearch.setOnLoadCallback(OnLoad);// register to be called at OnLoad when the page loads

    </script>
  </head>
  <body>
    <h1>Using Raw Searchers</h1>
    <form id="searcher">
      <table>
        <td class="search-form">
          <!-- googleのフォーム -->
          <div id="searchform">Loading</div>
        </td>
        
      </table>
    </form><!-- 検索結果-->
    <div id="results"></div>
  </body>
</html>