Windows 7 ProでXAMPP環境でGoutte を使用したスクレイピングができる環境を構築します。Goutteではブラウザ機能の実現に次のようなクラスを利用しています。
- Zend_Http_Client
- DomCrawler
- BrowserKit
これらの機能を組み合わせて、受け取ったCookieを次のリクエストで自動的に送信し、特定のリンクをクリックし、フォームに適切な値を詰めてPOSTしています。XAMPP環境で使用しているPHPのバージョンは5.4.31です。
Composerのインストール
Download ComposerのWindows InstallerからComposerをダウンロードし、ダウンロードされた「Composer-Setup.exe」を実行します。インストール途中に、php.exeの場所を確認するダイアログが表示されるので、C:\xampp\php\php.exeなどのように環境に合わせて指定します。
「C:\ProgramData\ComposerSetup\bin」のWindowsバッチファイル「composer.bat」をダブルクリックして実行するとPathが設定されます。コマンドプロンプトを開き、次のコマンドでインストールされているか確認します。
C:\>composer –version You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug Composer version 1.1.1 2016-05-17 12:25:44
Windowsバッチファイル「composer.bat」を実行しないと、Pathが設定されないので、上記のコマンドを実行すると、実行ファイルが存在しないというエラーになります。
Goutteのインストール
FriendsOfPHP/Goutteから、Goutteの圧縮ファイルGoutte-master.zipをダウンロードし、解凍します。解凍したGoutteフォルダのcomposer.jsonのあるディレクトリに、ディレクトリ「crawler」を作成して、そこに移動して、次のようにComposerを利用してGoutteをインストールします。
F:\Goutte-master\crawler>composer require fabpot/goutte
You are running composer with xdebug enabled. This has a major impact on runtime performance. See https://getcomposer.org/xdebug
Using version ^2.0 for fabpot/goutte
./composer.json has been created
Loading composer repositories with package information
Updating dependencies (including require-dev)
– Installing react/promise (v2.4.1)
Downloading: 100%
– Installing guzzlehttp/streams (3.0.0)
Downloading: 100%
– Installing guzzlehttp/ringphp (1.1.0)
Downloading: 100%
– Installing guzzlehttp/guzzle (5.3.0)
Downloading: 100%
– Installing symfony/polyfill-mbstring (v1.2.0)
Downloading: 100%
– Installing symfony/dom-crawler (v2.8.6)
Downloading: 100%
– Installing symfony/css-selector (v2.8.6)
Downloading: 100%
– Installing symfony/browser-kit (v2.8.6)
Downloading: 100%
– Installing fabpot/goutte (v2.0.4)
Downloading: 100%
symfony/browser-kit suggests installing symfony/process ()
Writing lock file
Generating autoload files
ここで次のエラーメッセージが発生することがあります。この場合、composer.jsonのあるディレクトリに、ディレクトリ「crawler」を作成して、そこに移動して、上記のコマンドを実行してください。
Root package ‘fabpot/goutte’ cannot require itself in its composer.json Did you accidentally name your root package after an external package?
Goutteの利用例
実際にGoutteを利用して、Yahooファイナンスから企業情報を取得してみます。
<?php
require_once(realpath(__DIR__) . "./Goutte-master/crawler/vendor/autoload.php");
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET', 'http://stocks.finance.yahoo.co.jp/us/profile/AAPL');
$crawler->filter('.boardFinCom tr')->each(function($node) {
echo "<dt>" . $node->filter('th')->text() . "</dt><br>";
echo "<dd>" . $node->filter('td')->text() . "</dd><br>";
});
?>
実行すると次の結果が取得できます。
概要
アップルは米国のIT機器大手。メディアデバイス、PC、スマートフォン、タブレット端末などのデザイン・製造・販売に従事し、主要製品は「iPhone」や「iPad」。2016年に「iPhone SE」、大型タブレット「iPad Pro」の新機種を発売予定。ウエアラブル端末「Apple Watch」、デジタルコンテンツやアプリも販売する。本社はカリフォルニア州。
英文社名
Apple Inc
本社所在地
1 Infinite Loop Cupertino, CA 95014 USA
電話番号
408 996-1010
設立年月日
1977年1月
代表者名
Mr. Timothy D. Cook
業種分類
IT・通信 (IT & Communications)
市場名
NASDAQ National Market System
従業員数
110,000人
ウェブサイト
www.apple.com
Goutte を使用してHTTPS経由でコンテンツの取得
<?php
require_once(realpath(__DIR__) . "./Goutte-master/crawler/vendor/autoload.php");
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET', 'https://example.com'');
echo $crawler->html();
?>
上記のようなコードでHTTPS経由でコンテンツを取得しようとしたところ、以下のようなメッセージで GuzzleHttp\Exception\RequestException がスローされました。
( ! ) Fatal error: Uncaught exception ‘GuzzleHttp\Ring\Exception\RingException’ with message ‘cURL error 60: See http://curl.haxx.se/libcurl/c/libcurl-errors.html’ in F:\AnimalflyUpdate\htdocs\swcraping\Goutte-master\crawler\vendor\guzzlehttp\guzzle\src\Exception\RequestException.php on line 51
次のように、requestメソッド実行前に「$client->getClient()->setDefaultOption(‘verify’, false)」を挿入すると、HTTPSのアドレスでもスクレイピングが可能となります。
<?php
require_once(realpath(__DIR__) . "./Goutte-master/crawler/vendor/autoload.php");
use Goutte\Client;
$client = new Client();
$client->getClient()->setDefaultOption('verify', false);
$crawler = $client->request('GET', 'https://example.com'');
echo $crawler->html();
?>
「setDefaultOption(‘verify’, false)」により、サーバー証明書の検証を行わないようにオプションを設定します。
テキストリンクの文字列を指定してリンクの取得
Crawler の selectLink メソッドを使って、テキストリンクの文字列を指定して(もしくは画像リンクのalt属性の文字列を指定して)リンクを取得することが出来ます。 このメソッドはリンクのノードを含む Crawler オブジェクトを返します。 この Crawler オブジェクトの link() メソッドを呼ぶことで、 Link のオブジェクトを取得出来ます。
<?php
require_once(realpath(__DIR__) . "./Goutte-master/crawler/vendor/autoload.php");
use Goutte\Client;
$client = new Client();
$crawler = $client->request('GET', 'https://tomosoft.jp/design/?p=6129');
//select a link
$link = $crawler->selectLink('Atmel Studioで開発したAT90USB162のLED点灯プログラム作成')->link();
//click to follow link
$crawler = $client->click($link);
echo $crawler->html();
?>
Link オブジェクトのメソッドを使って、リンクの情報を取得出来ます。
// リンクのURIを返す $uri = $link->getUri();