LoginSignup
5
6

More than 5 years have passed since last update.

読書メーターを goutte でスクレイピング

Last updated at Posted at 2016-04-26

読書メーターから自前の蔵書管理システムに移行したいのだがエクスポート機能がない。APIもない。
仕方ないのでスクレイピングした。
GitHub に上げるほどのこともないのでここに貼っておく。

  • 自分のアカウントにログインして「読んだ本」のASINと「読み終わった日(yyyymmdd)」を取ってくる。
  • goutte だがなぜか selectButton() でボタンのvalue文言からフォームの取得はできるのに selectLink() でアンカー文言からリンクの取得ができなかったのでURL指定してリクエストで遷移。
  • 動いた時点でやめたのでお見苦しい点がございます。
bookmeter.php
date_default_timezone_set('Asia/Tokyo');

require_once('./vendor/autoload.php');
//include './goutte-v3.1.0.phar';

// 出力ファイルパス
$csvPath = './books.csv';

// 読書メーターログイン情報:コマンドラインオプションから受け取る
/*
$opt = getopt('u:p:');
$mail = $opt['u'];
$pwd = $opt['p'];
*/
// 面倒ならベタ書きでもよい
$mail = 'YOUR_MAIL';
$pwd = 'PASSWORD';

$client = new \Goutte\Client();

$baseUri = 'http://bookmeter.com';

$cr = $client->request('GET', $baseUri.'/login');

// ログイン
$form = $cr->selectButton('ログイン')->form();
$form['mail'] = $mail;
$form['password'] = $pwd;
$cr = $client->submit($form);

// 読んだ本/リスト
//$cr = $client->click($cr->selectLink('読んだ本')->link());
$cr = $client->request('GET', $baseUri.'/home?main=book');

// ページナビから最後のページのページ番号を取得
$node = $cr->filter('span.page_navi_hedge a')->extract('href');
preg_match('/&p=(\d+)/', $node[0], $matches);   // /home?main=book&p=99"
$pLast = $matches[1];

for ($p = 1; $p <= $pLast; $p++)
{
    $cr = $client->request('GET', $baseUri . '/home?main=book&p=' . $p);
    printf("page: %d\n", $p);

    $nodes = $cr->filter('div.book_box_book_title a');
    foreach($nodes as $a)
    {
        $path = $a->getAttribute('href');
        $cr2 = $client->request('GET', $baseUri . $path);

        try {
            $form = $cr2->selectButton('更 新')->form()->getValues();
            $asin = $form['asin'];  // ASIN
            $date = $form['current_read_date']; // 読み終わった日
            printf("[%s][%s]\n", $asin, $date);

            // CSVに出力
            file_put_contents($csvPath, sprintf('"%s","%s"'."\n", $asin, $date), FILE_APPEND);

        } catch (Exception $e) {
            print $e->getMessage();
        }

        $client->back();
    }
}
5
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6