ニコニコデイリーランキングをパースしてみた
ここ数日ニコニコデイリーランキングを取得してみた。
6時にデータリセットとあったが、1時間ごとにデータを集計してランキングへ反映しているため、表示としては7時でリセットされる形でした。
6時台にデータを取得すればデイリーランキングを取得できる。
ランキングページは素敵にHTMLなので、パースが面倒。
tidyでHTMLをXHTMLに変換し、simplexmlでパースする方針で。
PHP: Tidy 関数 – Manualを確認するとコンパイルオプションひとつでいけそうなんだけど、やってみたらエラー。
checking for TIDY support... yes
configure: error: Cannot find libtidy
泣きそうになりながらもう一回コンパイルしたら通るし謎。
数日後には5.2.4をコンパイルしなきゃいけないせつなさ。
<?php
$config = array(
'output-xhtml' => true,
);
if (!$tidy = @tidy_parse_file('/path/to/file', $config, 'utf8')) {
echo 'tidy parse error';
exit;
}
$tidy->cleanRepair();
$xhtml = str_replace(' ', '', (string)$tidy);
unset($tidy);
if (!$simplexml = @simplexml_load_string($xhtml)) {
echo 'xml parse error';
exit;
}
$ranking = $simplexml->body[0]->table[0];
foreach ($ranking[0]->tr as $tr) {
if ($tr->td->attributes() == 4) {
continue;
}
print(preg_replace('/[^\d]/u', '', $tr->td[0]->p[0])); // ranking
print(preg_replace('/[^\d]/mu', '', $tr->td[0]->p[1])); // playing
print($tr->td[1]->p[1]->a->attributes()); // url
print(str_replace("\n", ' ', $tr->td[2]->div->h3->a)); // title
//exit;
}
xpath使わずやってみたけど何がなんだか。
対象ページのフォーマット変わったら、ユーザー定義のエラーハンドラーでとれないUndefined functionでE_USER、syntax errorでE_PARSEがでて死亡。
それに対するエラー処理を@エラー抑制子がんばること考えるとxpathの方使ったほうが良いなと思った。
カテゴリー: 日記