PHPからwebページのスクレイピングを行うための有名なライブラリにphpQueryがあります。
phpQueryを使用すると、htmlに対してjQueryのようなセレクタで、取得したいタグの検索などが簡単に行えるので便利です。
今回はこのphpQueryをcomposer経由でインストールしたうえで、簡単な動作確認を行ってみました。
作業手順
phpQueryパッケージをインストールする
まず、
composer self-update
コマンドでcomposer自身のアップデートを行ったうえで、requireコマンドを使用してphpqueryパッケージのインストールを行います。composer self-update
composer require electrolinux/phpquery
composer reuireでインストールができたら、
composer info
コマンドで正しくインストールできたか確認します。今回試した時点ではver0.9.6が最新のバージョンでした。> composer info electrolinux/phpquery
You are running Composer with SSL/TLS protection disabled.
name : electrolinux/phpquery
descrip. : phpQuery is a server-side, chainable, CSS3 selector driven Document Object Model (DOM) API based on jQuery JavaScript Library
keywords :
versions : * 0.9.6
type : library
license : MIT License (MIT) (OSI approved) https://spdx.org/licenses/MIT.html#licenseText
source : [git] https://github.com/electrolinux/phpquery.git 6cb8afcfe8cd4ce45f2f8c27d561383037c27a3a
dist : [zip] https://api.github.com/repos/electrolinux/phpquery/zipball/6cb8afcfe8cd4ce45f2f8c27d561383037c27a3a 6cb8afcfe8cd4ce45f2f8c27d561383037c27a3a
names : electrolinux/phpquery
インストールしたパッケージの動作確認を行う
動作確認のために簡単なプログラムを作ってみます。
なんでもよいのですが、今回はcomposerのパッケージが検索できるサイトから、名前に”helloworld”を含むパッケージの一覧を取得してみます。
一度ブラウザでアクセスしてみるとわかるのですが
https://packagist.org/search/
のページへ、クエリストリング?q=helloworld
を付与したURLで検索が結果が表示され、各パッケージのタイトルはh4タグの中に記載されています。<?php
require 'fuel/vendor/autoload.php';
// composerのパッケージ一覧から、名前に"helloworld"を含むパッケージを取得
$htmlStr = file_get_contents("https://packagist.org/search/?q=helloworld");
// htmlテキストをスクレイピングして、h4タグの一覧を取得
$dom = phpQuery::newDocument($htmlStr);
$titles = pq($dom)->find("h4");
// 取得したすべてのh4タグタイトルを画面に出力
foreach( $titles as $title ) {
echo trim( pq($title)->text() ) . "\n";
}
上記のプログラムを実行してみた結果が以下の通りです。
想定通り、helloworldな名前を持つパッケージたちが取得できました。
> php test_phpquery.php
reps_demo/helloworld
brooklab/helloworld
abbert/helloworld
dnconcept/hello-world
nsdhami/hello-world
bagwaa/hello-world
vsonx/hello-world
hurad/hello-world
vdrizheruk/hello-world
eric-clinton/helloworld
wyanez/zf2-helloworld
mshige1979/helloworld
joomlatools/com_helloworld
digitalformula/hello-world
donut/hello_world
関連記事
コメントを残す