PHPでGoutteを用いてスクレイピングをおこなう

概要

スクレイピングを行う場合、 よく用いれられる言語として、PythonRuby,node.jsなどがあげられると思います

PHPでも基本的ななことはできるので、スクレイピングライブラリといくつかの例を紹介します

利用ライブラリ

Goutte

SymfonyのCssSelector and DomCrawlerとGuzzleを組み合わせたライブラリで、 Symfonyのライブラリが優秀なこともあり、単発で単一ページをスクレイピングするには十分な機能が揃っています

実行した環境

Ubuntu 16.04.1 LTS
PHP 7.0.22-0ubuntu0.16.04.1 (cli) ( NTS )

Goutteをインストール

composer require fabpot/goutte

Usage

基本的な利用方法

        $client = new Client();
        $url = 'URL';
        $crawler = $client->request('GET',$url);
        $crawler->filter('h2 > a')->each(function ($node) {
          print $node->text()."\n";
        });

CSSセレクタで指定

        // CSSセレクタでの指定
        $crawler->filter('h2 > span')->each(function ($node) {
            echo "{$node->text()}\n";
        });

XPathでの指定

        $crawler->filterXPath('//*[@id="mw-content-text"]/div/ul/li')->each(function ($node) {
            echo "{$node->text()}\n";
        });

単一nodeの取得

        // とりあえず最初のnodeがほしい
        $node = $crawler->filter('p > b')->first();
        echo "{$node->text()}\n";
        // もちろんCSSセレクタなので、クラス指定もOK
        $node = $crawler->filter('.mw-headline')->first();
        echo "{$node->text()}\n";
        // ユニークなXPathでの取得
        $node = $crawler->filterXPath('//*[@id="mw-content-text"]/div/ul[10]/li[1]');
        echo "{$node->text()}\n";

画像一覧を取得

        // 画像一覧 実際にはスキーム省略や相対パスへの対応が必要
        $crawler->filter('img')->each(function ($node) {
            echo "{$node->attr('src')}\n";
        });

まとめ

上記のようにPHPでも基本的なスクレイピングは簡単にできます

単発的な目的であれば、PHPでも使っていけます!

参考リンク

github.com

symfony.com

Guzzle, PHP HTTP client — Guzzle Documentation