利用Yahoo! Search API开发自已的搜索引擎-javascript版

1/5/2008来源:Java教程人气:6516


  美国东部时间3月1日,雅虎公司联合创始人之一的杨致远将公布公司的搜索网络将进入Web服务。雅虎公司在www.developer.yahoo.com网站建立了Yahoo Search Developer Network,公司计划在此纽约举行的搜索引擎战略大会(Search Engine Strategies Conference)上推出这一计划。该网络将答应开发者在雅虎搜索之上建立新的应用程序,其中包括图像、视频、新闻以及地区搜索等内容。想要使用这项服务的会员必须先去http://api.search.yahoo.com/webservices/register_application  申请一个自已的ID号,注:每个ID号天天只能搜索5000次。

    下面我们看一下,如何用javascript脚本调用Yahoo! Search API实现搜索的效果,全部脚本如下:
  

/*
 * yahoo_search_api.js
 * Part of the Yahoo! Search Sidebar for Firefox
 * powered by Yahoo! Search web services (http://api.search.yahoo.com)
 * Written by Marc Abramowitz (http://marc.abramowitz.info)
 * Copyright (C) 2005 Yahoo! Inc.
 * www.knowsky.com
 */

function Yahoo_Search() {}

Yahoo_Search.baseURL = function () {
  return "http://api.search.yahoo.com/WebSearchService/V1/";
}

Yahoo_Search.appid = function () {
  return "YahooSearchSidebar";
}

Yahoo_Search.baseArgs = function () {
  return "appid=" + this.appid();
}

Yahoo_Search.Results = function (args) {
  var xmlUrl = this.baseURL() + "webSearch?"
       + this.baseArgs()
       + "&query=" + args["Doc"]
       + "&zip="
       + "&start=" + args["First"]
       + "&results=" + args["Count"];
  var xmlhttp = new XMLHttPRequest();
  xmlhttp.open("GET", xmlUrl, false);
  xmlhttp.send(null);
  return this.readXML(xmlhttp.responseXML);
}

Yahoo_Search.readXML = function (xmlDoc) {
  try {
    var retVal = new Array();
    var resultSet = xmlDoc.getElementsByTagName("ResultSet")[0];
    var totalResultsAvailable = parseInt(resultSet.getAttribute("totalResultsAvailable")); 
    var totalResultsReturned = parseInt(resultSet.getAttribute("totalResultsReturned"));
    var firstResultPosition = parseInt(resultSet.getAttribute("firstResultPosition"));
    var start = firstResultPosition;
    var end = firstResultPosition + totalResultsReturned - 1; 
    var results = xmlDoc.getElementsByTagName("Result");
    for (var i = 0; i < results.length; i++) {
      var result = results[i];         
      var title = result.getElementsByTagName('Title')[0].firstChild.nodeValue;
      var summary = '';
      if (result.getElementsByTagName('Summary')[0].firstChild) {
        summary = result.getElementsByTagName('Summary')[0].firstChild.nodeValue;
      }
      var clickUrl = result.getElementsByTagName('ClickUrl')[0].firstChild.nodeValue;
      var url = result.getElementsByTagName('Url')[0].firstChild.nodeValue;
      retVal[i] = { I: start + i, Title: title, Summary: summary, ClickUrl: clickUrl, Url: url };
    }