リンク収集 - Mozilla Java Html Parserを使ってみる。 2009/06/13

HTMLに存在するリンク(aタグのhrefがあるもの)をひろいだしたいと思ったのでした。
htmlパーサーはいろいろあるようですが、Mozilla Java Html Parserを使ってみます。



実は、以前、試そうとして、ネイティブライブラリを使うことを知って、環境変数の設定が面倒だと思い、使わずじまいでした。

今回はosx上のEclipse上で動かしてみます。

僕の環境変数の設定は、実行する際の「Run configurations」のEnvironmentを利用しました。
mac osxの場合は、DYLD_LIBRARY_PATHを設定します。



以下コードです。
package aaa;

import static quicklunch.e2.goodies.utils.ObjectUtils.eq;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.dappit.Dapper.parser.MozillaParser;

public class A_リンク収集 {

public static void main(String[] args) throws Exception {
test();
}

static String get_html(String surl, String enc)
throws MalformedURLException, IOException {
URLConnection connection = new URL(surl).openConnection();
connection.connect();
BufferedInputStream in = new BufferedInputStream(
(InputStream) connection.getContent());

return get(in, enc);
}

public static String get(InputStream in, String enc) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
int len = 0;
byte[] bs = new byte[8192];
while ((len = in.read(bs)) != -1) {
outputStream.write(bs, 0, len);
outputStream.flush();
}
outputStream.close();
} finally {
in.close();
}
String s = new String(outputStream.toByteArray(), enc);
return s;
}

public static String get_file(String filepath, String enc)
throws IOException {

BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
filepath));
return get(bis, enc);
}

static void test() throws Exception {
String s = get_html("http://deiji.jp", "utf-8");
MozillaParser.init();
Document document = new MozillaParser().parse(s);
System.out.println(getLink((Node) document.getDocumentElement()));
}

public static class Link {
String title;
String link;

public Link(String title, String link) {
this.title = title;
this.link = link;
}

public String toString() {
return title + ":" + link;
}
}

public static List<Link> getLink(Node node) {
List<Link> list = new ArrayList<Link>();
switch (node.getNodeType()) {
case Node.ELEMENT_NODE:
NamedNodeMap attrs = node.getAttributes();
if (eq(node.getNodeName(), "a")
&& attrs.getNamedItem("href") != null) {
String link = attrs.getNamedItem("href").getNodeValue();
NodeList nl = node.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node n2 = nl.item(i);
if (n2.getNodeType() == Node.TEXT_NODE) {
list.add(new Link(n2.getNodeValue(), link));
}
}
}

for (Node child = node.getFirstChild(); child != null; child = child
.getNextSibling()) {
list.addAll(getLink(child));
}
}
return list;
}
}

: