- 2008-05-06 (火) 14:25
- PHP
Twitter API を使っても過去の user_timeline を取得できないので、PHP で直接 Web をスクレイピングして取得してみました。
環境
・PHP 5.2.3
・PEAR::HTTP_Client を使用
取り出す内容
・id
・メッセージ(text)
・permalink
・発言日時
コード(クラス)
<?php
require_once 'HTTP/Client.php';
class Twitter_Scrape {
private $statuses;
public function __construct () {
}
public function getTimeline ($username, $page = 1) {
$url = 'http://twitter.com/'.$username.'?page='.$page;
$client =& new HTTP_Client();
$client->get($url);
$response = $client->currentResponse();
$res = mb_convert_encoding($response['body'], 'UTF-8', 'UTF-8,SJIS,EUC-JP,JIS');
$dom = @DOMDocument::loadHTML($res);
if ($dom) {
$xml = simplexml_import_dom($dom);
if ($xml) {
$i = 0;
// $page が 1 の場合は最新の発言を取得する
if ($page == 1) {
$entries = $xml->xpath('//div[@class="desc hentry"]');
$content = $entries[0]->xpath('p[@class="entry-title entry-content"]');
$meta = $entries[0]->xpath('p[@class="meta entry-meta"]');
$statuses[$i++] = array(
'id' => substr($meta[0]->a[0]['href'], -9),
'text' => strip_tags($content[0]->asXML()),
'permalink' => $meta[0]->a[0]['href'],
'date' => $meta[0]->a[0]->abbr['title']
);
}
// ページ内の発言を取得する
// URL が長いと途中で切れてしまう...
$entries = $xml->xpath('//tr[@class="hentry"]');
foreach ($entries as $entry) {
$content = $entry->xpath('td[@class="content"]');
$meta = $content[0]->xpath('span[@class="meta entry-meta"]');
$statuses[$i++] = array(
'id' => substr($entry['id'], 7),
'text' => strip_tags($content[0]->span[0]->asXML()),
'permalink' => $meta[0]->a[0]['href'],
'date' => $meta[0]->a[0]->abbr['title']
);
}
return $statuses;
} else {
print ('xml parse error');
}
} else {
print ('dom parse error');
}
}
}
?>
コード(呼出元)
<?php
require_once "twitter_scrape.class.php";
$req = new Twitter_Scrape();
$statuses = $req->getTimeline('yusuke0927', 1);
foreach ($statuses as $status) {
print('<tr>');
print('<td>'.$status['id'].'</td>');
print('<td>'.$status['text'].'</td>');
print('<td>'.$status['permalink'].'</td>');
print('<td>'.$status['date'].'</td>');
print('</tr>');
}
?>
簡単な説明
インスタンスを生成して、getTimeline でユーザ名とページ数を渡すと、スクレイピングした結果を連想配列で返します。
問題点
発言に含まれる URL が長いと切れたままになってしまう。これは発言を asXML で取得した後に strip_tags でタグを除去しているせい。なんとかしたい。
関連する記事
Comments:0
Trackbacks:0
- Trackback URL for this entry
- http://www.sukechan.net/archives/61/trackback/
- Listed below are links to weblogs that reference
- PHP で Twitter をスクレイピングする from sukechan.net

