PHPでスクレイピングその1


Goutte

PHPで簡単にスクレイピングを行うことができるライブラリーです。

導入

コンポーザーでインストール

$ composer require fabpot/goutte

もしくは上記Githubから.pharファイルをダウンロードしましょう

あとはソース内で

test.php
require_once './vendor/autoload.php';

test.php
require_once 'goutte.phar';

のように読み込んであげて、

test.php
use Goutte\Client;

useしてあげるだけでOKです!

使ってみる

https://giftpad.co.jp/company こちらのサイトから

赤枠の部分、良い言葉なので是非PHPで取得したいですね

XPathを確認して、

ソースに反映

index.php
<?php

require_once 'goutte.phar';

use Goutte\Client;

// Goutteオブジェクトの生成
$client = new Client();

// ページ情報を取得
$crawler = $client->request('GET', 'https://giftpad.co.jp/company');

// タグを指定
$word = $crawler->filter('div#content div section div div div p')->each(function($element){
    return $element->text();
});

echo $word[0];

取れました!

総評

  • 簡単に導入できて、XPathやタグの指定で直感的にスクレイピングしやすいと感じました。
  • 今回は簡単な紹介でしたが、次回は取得したデータをもとにして何かのツールを作ろうと思います。