PHPでさくっとスクレイピングしたい。SimpleScrape
これは、
SimpleXmlとSimpleTag比較:twitterのhomeをスクレイピングしてみた。 - gounx2の日記
SimpleTag と SimpleXML->xpath の比較 (rev3115) - gounx2の日記
でやったことのまとめ的なものです。
では、本題です。
これは何か?
コンテンツを http get で取ってきて、tag&id、tag&class で絞込み。
という、スクレイピングをPHPで簡単に書ける SimpleScrape を作ってみました。
rhacoのSimpleTagを使っているので、php4でも使えます。
SimpleScrape | 等価なxpath式 |
---|---|
selectTagId('div') | //div |
selectTagId('div', 'content') | //div[@id="content"] |
selectTagClass('div', 'hentry') | //div[contains(concat(" ",@class," ")," hentry ")] |
記述例
例えばこんな感じで使います。
$urlからhttpでコンテンツを取ってきて、select* で絞込み。
// '//div[@id="content"]//div[contains(concat(" ",@class," ")," hentry ")]' $scr = SimpleScrape::loadUrl($url); $scr->selectTagId( 'div', 'content'); $scr->selectTagClass('div', 'hentry');
結果をstringで得る。
$str = $scr->getValue(); // stringで結果を得ます。結果が複数あっても、先頭のものだけ返します。 $str = $scr->getValue(1); // idx指定もできます。 $arr = $scr->getValues(); // arrayで全部の結果を得ます。
SimpleTagで結果を得ることもできます。
$tags = $scr->getSimpleTags(); // 結果をSimpleTagの配列で得ます。
サンプル
Twitterのhomeのタイムラインをスクレイピングするサンプル&ソースです。
http://goungoun.dip.jp/app/open/rhaco-sample/simpletag004.php?name=goungoun
http://goungoun.dip.jp/app/open/rhaco-sample/simpletag004.phps
http://goungoun.dip.jp/app/open/rhaco-sample/SimpleScrape.phps
おまけ
$scr->selectTag('tr', 'id', '/^status/', true, true);
と書けば、
- trで、
- idが 正規表現 /^status/
- と一致するものを抽出
になります。