晴歩雨描

晴れた日は外に出て歩き、雨の日は部屋で絵を描く

「PHP Simple HTML DOM Parser」で、Webスクレイピング(HTMLから情報を抽出)。

PHP Simple HTML DOM Parser」で、Webスクレイピング(HTMLから情報を抽出)を試してみた。

以下のWebページを参考にした。

以下からPHPライブラリをダウンロードする。

「simple_html_dom.php」を読み込む。

<?php
require_once('simple_html_dom.php');
?>

例えば、次のような価格.comの一覧リストから製品名を抽出する。

https://kakaku.com/camera/camera-lens/itemlist.aspx?pdf_Spec101=1&pdf_Spec102=1&pdf_Spec103=35

≪HTMLの抜粋≫

<table>
<tr>
<td class="ckitemLink">
<a href="https://kakaku.com/....." class="ckitanker"><span>メーカー名</span>製品名</a>
</td>
<td class="addFavoriteBtn">・・・・</td>
</tr>
</table>

上記の様なHTMLから製品名が入っているclass名「ckitemLink」の中を抜き出すソースは以下。

<?php
require_once('simple_html_dom.php');
parse('https://kakaku.com/camera/camera-lens/itemlist.aspx?pdf_Spec101=1&pdf_Spec102=1&pdf_Spec103=35');
function parse($url) {
	$html = file_get_html($url);
	foreach ($html->find('.ckitemLink') as $element) {
		echo $element->outertext.'<br>'."\n";
	}
}
?>

=> 処理結果サンプル:https://ok2nd.sakura.ne.jp/parse/kakaku-1.php

class名「ckitemLink」の中の<a>タグ内だけを抜き出すソースは以下。

<?php
require_once('simple_html_dom.php');
parse('https://kakaku.com/camera/camera-lens/itemlist.aspx?pdf_Spec101=1&pdf_Spec102=1&pdf_Spec103=35');
function parse($url) {
	$html = file_get_html($url);
	foreach ($html->find('.ckitemLink a') as $element) {
		echo $element->outertext.'<br>'."\n";
	}
}
?>

=> 処理結果サンプル:https://ok2nd.sakura.ne.jp/parse/kakaku-2.php

<a>タグ内のタイトルとURLをそれぞれ別々に抜き出す。

<?php
require_once('simple_html_dom.php');
parse('https://kakaku.com/camera/camera-lens/itemlist.aspx?pdf_Spec101=1&pdf_Spec102=1&pdf_Spec103=35');
function parse($url) {
	$html = file_get_html($url);
	foreach ($html->find('.ckitemLink a') as $element) {
		echo $element->plaintext.' ■ ';
		echo $element->href.'<br>'."\n";
	}
}
?>

=> 処理結果サンプル:https://ok2nd.sakura.ne.jp/parse/kakaku-3.php