KOYAMA Yoshiaki のブログ

プログラミングについての試行錯誤をつらつら書き溜めていきます。

PeanutsView

プログラムの動作は単純です。簡単に説明すると、フレームのサイズをゼロにした WebView を作成し、 http://snoopy.com/ からデータを読み込みます。mainFrame から DOMDocument を取り出し、DOMHTMLDocument に変換、そこから images メソッドを使って画像をリンクしている DOMNode ( DOMElement ) を集めた DOMCollection を取り出します。


後は DOMCollection から DOMNode を順番に取り出し、DOMElement に変換、getAttribute:@"SRC" を呼び出し、取り出した attribute の文字列と @"/comics/peanuts/archive/images/peanuts" で始まる文字列を比較し、一致した場合 src に格納します。後は URL を作成し、NSImage を使って画像を Web から取り出して表示します。


下記はソースから重要な箇所を抜粋したものです。詳細はソースを参照してください。

 _webView = [[WebView alloc] initWithFrame:NSZeroRect];
[_webView setFrameLoadDelegate:self];

frame = [_webView mainFrame];
url = [NSURL URLWithString:@"http://snoopy.com/"];
request = [NSURLRequest requestWithURL:url];

[frame loadRequest:request];
frame = [_webView mainFrame];
htmlDocument = (DOMHTMLDocument *)[ frame DOMDocument ];

collection = [htmlDocument images];

for (i=0; i<[collection length]; i++) {
	element = (DOMElement *)[collection item:i];
	if ([[element getAttribute:@"SRC"] compare:peanuts 
		options:NSCaseInsensitiveSearch range:range] == NSOrderedSame) {
		src = [element getAttribute:@"SRC"];
	}
}

image = [[NSImage alloc] initWithContentsOfURL:url];