2009-05-17

SlothLib - 6. YahooJpWebElement (중)

그러면 영문검색엔진에서 YahooJpWebElement를 사용하는 방법을 연구해 보자.

일단 참조를 추가하는 것은 (상)편 1, 2번의 방법과 동일하다.
이렇게 참조를 추가하면 SlothLib가 제공하는 인터페이스를 사용할 수 있게 된다.

함수를 하나 만들어 보기로 하자.
입력은 검색어인 Querystring과 요망 검색결과수인 Count 변수로 하고
출력은 검색 결과 자체로 생각해 보자.

웹 소스를 얻어올 수 있는 방법은 2가지인데,
가장 간단한 것은 WebClient 개체를 이용하는 것이다.
그러나 이 방법은 대상 웹 소스가 많을 때는 부하가 걸리므로
WebRequest, WebResponse를 이용하는 방법을 추천한다.

using System.IO;
using System.Xml;
using System.Xml.XPath;
using SlothLib.Web.Search;

private void ResultBoss (string QueryString, string Count)
{
   // 검색결과를 저장할 개체 차용 - YahooJpWebElement 개체를 빌려옴
   List<YahooJpWebElement> ResultElementList = new List<YahooJpWebElement>();

   string tQuery = "http://boss.yahooapis.com/ysearch/web/v1/"+ QueryString.Trim() + "?format=xml&count=" + Count + "&appid=받은 API Key";

 try
 {
   // 원시 검색결과 획득
   HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(tQuery);
   HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
   Stream myStream = myResponse.GetResponseStream();

   // XML 형태로 변환
   XmlDocument xmlDoc = new XmlDocument();
   xmlDoc.Load(myStream);
   myStream.Close();
   myResponse.Close();

   // 루트요소 획득
   XmlElement xmlRoot = xmlDoc.DocumentElement;

   // 검색 결과수 추출 및 저장
   XmlNodeList xHitPath = xmlRoot.GetElementsByTagName("resultset_web");
   foreach (XmlElement xe in xHitPath)
   {
      Hit = xe.GetAttribute("totalhits");
   }

   // 검색 결과 추출 및 저장
   XmlNodeList xmlResultList = xmlRoot.GetElementsByTagName("result");
   int rank = 0;

   foreach (XmlElement xmlResult in xmlResultList)
   {
      rank++;
      string title = GetElementString(xmlResult.GetElementsByTagName("title"));
      string summary = GetElementString(xmlResult.GetElementsByTagName("abstract"));
      string url = GetElementString(xmlResult.GetElementsByTagName("url"));
      string date = string.Empty;
      string clickurl = GetElementString(xmlResult.GetElementsByTagName("ClickUrl"));
      string mimetype = string.Empty;
      string cacheUrl = string.Empty;
      string cacheSize = string.Empty;

      YahooJpWebElement result = new YahooJpWebElement(rank, title, summary, url, clickurl, mimetype, date, cacheUrl, cacheSize);
      ResultElementList.Add(result);
   }
 }
 catch (Exception e)
 {
   MessageBox.Show(e.ToString());
 }
}

private string GetElementString(XmlNodeList nodeList)
{
   if (nodeList.Count == 0)
      return string.Empty;
   else
      return nodeList[0].InnerText;
}

No comments:

Post a Comment