Yahoo! JAPAN の RSS一覧 - Yahoo!検索データ を見ると、通常の Web 検索による話題のキーワードは RSS フィードで取得することができるようになっている。でも、 Twitter などのリアルタイム検索での話題のキーワードは RSS フィードで提供されていない。

そういうわけで、 急上昇中 つぶやき - Yahoo!検索データ を Java + JTidy でスクレイピングして、話題のキーワードを取得するサンプルを書いてみた。


import java.io.*;
import java.net.*;
import javax.xml.xpath.*;
import org.w3c.dom.*;
import org.w3c.tidy.Tidy;
 
public class RealtimeBuzz {
 
  public static void main(String[] args) throws Exception {
    String[] words = RealtimeBuzz.getWords();
    for (String word : words) {
      System.out.println(word);
    }
  }
 
  public static String[] getWords() throws Exception {
    Document doc = getHtmlDoccument("http://searchranking.yahoo.co.jp/realtime_buzz/");
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    NodeList h3list = (NodeList) xpath.evaluate(
      "//div[@class='listRowlink']/ul[@class='patf']//h3",
      doc,
      XPathConstants.NODESET);
    String[] words = new String[h3list.getLength()];
    for (int i = 0; i < h3list.getLength(); i++) {
      words[i] = getValue(h3list.item(i));
    }
    return words;
  }
 
  /**
   * JTidy を使って org.w3c.dom.Document を取得する。
   * @param url 対象WebページのURL
   * @return org.w3c.dom.Document オブジェクト
   * @throws IOException
   */
  private static Document getHtmlDoccument(String url) throws IOException {
    URLConnection con = new URL(url).openConnection();
    Tidy tidy = new Tidy();
    tidy.setShowErrors(0);
    tidy.setShowWarnings(false);
    tidy.setQuiet(true);
    tidy.setInputEncoding("utf-8");
    tidy.setOutputEncoding("utf-8");
    tidy.setShowErrors(0);
    tidy.setForceOutput(true);
    Document doc = tidy.parseDOM(con.getInputStream(), null);
    return doc;
  }
 
  private static String getValue(Node node) {
    if (node.hasChildNodes()) {
      return getValue(node.getFirstChild());
    } else {
      return node.getNodeValue();
    }
  }
}

サンプルコードの実行結果。


刀剣乱舞
石鹸屋
ギャン子
へしこ
東京ビッグサイト
トライゼータ
ソルティーシュガー
笑コラ
葛西臨海水族園
ジェガン
どんと祭
依頼札
アーケードゲーム
斎藤工
しんけん
艦これアーケード
韓国 保育園
村人グランプリ
ルーカス
ウズベキスタン
少クラ
アドウ
ケンペス
セカホン
とうらぶ
春菊
厚労省年金マンガ
ポリアセタール
テレビジョンzoom
産婆

最近なら、 Java で Web ページをスクレイピングするライブラリとしては、 Camelを使ったJavaスクレイピング - Qiita とか Java - jsoup使い方メモ - Qiita とか使うのもいいかなと思った。思ったけど、 XPath で書いたほうが標準っぽくていいかなということで、やっぱり JTidy を使うことに。

tags: java buzz jtidy twitter yahoo search

Posted by NI-Lab. (@nilab)