PHP(ハイパーテキストプリプロセッサー)は、ウェブデータ収集に利用できるウェブ開発用のスクリプト言語です。本記事では次の内容を取り上げます:
PHPを使う理由
PHPは現在、WordPress、Slack. などのサイトを含め、ウェブサイトの約40%を動かしています。ウェブ開発において最も人気のあるサーバーサイドスクリプト言語の一つです。MySQL を使用している人にとって、両者のデータベースは密接に関連しています。比較的習得しやすい言語であり、ドキュメントやライブラリも充実しているため、開発期間を短縮できます。
PHPの紹介
This guide will introduce a method of manual web scraping in which you send a bot to a web server and collect data using PHP as the foundational programming language. This is as opposed to using a fully automated data collection tool that can simplify and streamline the process.
ウェブスクレイパーは、サーバーにHTTPリクエストを送信し、ウェブサイトのコードを収集することで機能します。以下では、得られた情報をどのように分析するかを紹介します。
以下は、スクレイピングしたいウェブサイトの見出しに表示されるコードスニペットの例です:
<html><body><h1>This is a heading!</h1></body></html>
このコードを取得したら、人間の分析者が読んで理解できるように解析されなければなりません。この例では、パース後に、以下のようなプレーンテキストが残ります:
‘This is a heading!’
始める前に、お使いのコンピュータにPHPがインストールされていることを確認してください。
PHPによるウェブスクレイピングの簡単な3ステップ
手順1:ターゲットWebサイトのコードを収集します。
次のコードを入力して始めます:
<?php
$code = file_get_contents (“http://quotes.toscrape.com”);
?>
コーディング規約に関して:
- “<?php” and “?>” are used in all PHP documentation at the beginning and the end of commands.
- The second line sets a variable called “$code” that pertains to the contents of the URL in question, in this example, we will be targeting: “http://quotes.toscrape.com”. This helps store the URL code inside of the “$code” variable.
完全自動のウェブスクレイピングソリューションをご希望ですか?
手順2:ウェブページの解析
この作業は、本サイトに掲載されているすべての引用文を収集することを目的としています。
目的のページで右クリックし、「ページのソースを表示」をクリックすると、ソースコードが表示された新しいウィンドウが開きます。この例では、すべての引用符がタグの中に入っており、itemprop属性も「text」に設定された “text “クラスで、次のように表示されています。
まず、PHPを利用して、タグの中にある引用符以外の不要なテキストを取り除き、「echo」関数を使って画面に表示することから始めます:
<?php
$code = file_get_contents("http://quotes.toscrape.com");
$code = str_replace(">", "<>", $code);
$splitCode = explode("<", $code);
// Find the first occurance of the opening tag of the quotes:
$openingTag = array_search('span class="text" itemprop="text"', $splitCode, true);
// Find the first occurance of the closing tag of the quotes
$closingTag = array_search('/span', $splitCode, true);
// Now, find the text in between the tags
$i = $openingTag;
$total = "";
while ($i < $closingTag) {
$total = $total . $splitCode[$i];
$i = $i + 1;
}
$final = substr($total, 37);
echo $final;
?>
2行目では、コード中の”>”を””に置き換えています。これは、5行目の”タグの位置を、11行目で末尾のタグの位置を検索しています。
あとは、この2つの間にあるテキストを取り出せばいいだけです。そのためには、開始タグ変数の位置の値で「i」という変数を作成します。そして、その結果を後で入力するための変数を作成します。16行目で、開始タグの後の各文字をループし始め、その文字を合計値に加え、変数「i」を増加させています。終了タグを過ぎると、ループは停止します。
次に、最終的な文字列の最初の37桁を削除します。この最初の37桁は、解析対象のタグ、つまりタグの中にある数字であるためです。最後に、「echo関数」を使って最終結果を取得します。
プログラムを実行すると、次のような画面が表示されます:
“The world we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
これは、「非人間的」なコードを一切使わずにスクレイピングしているウェブサイトに表示される最初の引用文です。
手順3:ループスルー
お気づきかもしれませんが、最初の1回しか収集せず、それ以降は一収集しません。これを解決するには、今返したオカレンスを削除して、全部を取得するまでこのプロセスを繰り返します。さらに、スクレイピング処理を関数に落とし込み、必要なときにいつでも実行できるようにすることで、コードを簡素化できます。このコードを利用してみてください:
<?php
$code = file_get_contents("http://quotes.toscrape.com");
$code = str_replace(">", "<>", $code);
$splitCode = explode("<", $code);
function parseCode($splitCode) {
// Find the first occurance of the opening tag of the quotes:
$openingTag = array_search('span class="text" itemprop="text"', $splitCode, true);
// Find the first occurance of the closing tag of the quotes:
$GLOBALS[closingTag] = array_search('/span', $splitCode, true);
// Now, find the text in between the tags
$i = $openingTag;
$total = "";
while ($i < $GLOBALS["closingTag"]) {
$total = $total . $splitCode[$i];
$i = $i + 1;
}
// Run the function, then update splitCode to delete the previous occurance
// that it can be repeated for the next quote, then loop through 3 times
// (You can change how many times):
parseCode($splitCode);
$splitCode = array_slice($splitCode, $GLOBALS["closingTag"]-1, NULL, TRUE);
parseCode($splitCode);
$splitCode = array_slice($splitCode, $GLOBALS["closingTag"]-1, NULL, TRUE);
parseCode($splitCode);
$splitCode = array_slice($splitCode, $GLOBALS["closingTag"]-1, NULL, TRUE);
parseCode($splitCode);
?>
先のコードが「parseCode」という関数に入力され、「$splitCode」というパラメータを含んでいることにお気づきでしょうか。この関数がコードにアクセスし、その結果を「エコー」することができるようになっています。27行目で「parseCode」関数が実行され、28行目で前の閉じタグを削除し、複製できるようにします。27行目と28行目は、プログラムがパターンを識別し、次の出現を発見できるように、単純に3回繰り返されています。
最後に、閉じタグをスーパーグローバルスコープ「$GLOBALS」の「グローバル変数」として入力し、21行目で、返す各行の周りに<p>タグを入力して、解析する新しい引用符ごとに新しい行を作成するようにしています。その結果がこれです:
“The world we have created it is a process of our thinking. It cannot be changed without changing our thinking.”
“There are only two ways to live your life. One is as though nothing is a miracle. The Other is as though everything is a miracle.”
“Try not to become a man of success. Rather become a man of value.”
The result is exactly what we were looking for. No code, just readable text. This process can be replicated for nearly any target site, such as scraping eBay for target data points such as product pricing, reviews, and SKUs (Stock Keeping Units).
キーポイント
PHPを使用して対象データをウェブ上でスクレイピングすることは、時間や手間のかかる作業ではありますが、効果的な方法と言えます。企業が検討すべき現実的な選択肢は、すぐに使えるデータセットの購入です。これにより、時間とリソースを節約し、ご自身やチームは事業の拡大、顧客満足の確保、コア製品の開発に全力を注ぐことができます。