Goutte スクレイピング解析時のスニペットメモ

Goutteをいろいろいじったので備忘録。

classが2つあるタグを取得する

html : <div class=”class1 class2″>
php  : $crawler->filter(‘div.class1.class1’);

idを指定で指定する

html : <div id=”hello”>
php  : $crawler->filter(‘div#hello’);

Imgタグのsrcを取得

html : <img src=”http://reafo.net/image.png”>
php  : $crawler->filter(‘img’)->attr(‘src’);

htmlのタグごと取得する

html : <div class=”catchMeIfYouCan”><span id=”hello”>てきすと</span>ですよ</div>
php  : $crawler->filter(‘catchMeIfYouCan’)->html();

Tableタグのタイトルを判定して中身を取得する

html : <table><tr><th>タイトル1</th><td>文章</td></tr><tr><th>タイトル1</th><td>文章</td></tr></table>
php  :
$crawler->filter(‘table tr’)->each(function($element){
$th = $element->filter(‘th’)->text();
$td = $element->filter(‘td’)->text();

if($th =””){ /* …  */}
});

thタグを使わずにtdのみを使用している場合
html : <table><tr><td>タイトル1</td><td>文章</td></tr><tr><td>タイトル1</td><td>文章</td></tr></table>
php  :
$crawler->filter(‘table tr’)->each(function($element){
$th = $element->filter(‘td’)->eq(0)->text();
$td = $element->filter(‘td’)->eq(1)->text();

if($th =””){ /* …  */}
});

参照

下記サイトを参考にしました。
WebスクレイピングライブラリGoutteで遊んでみる
Goutteを使用してHTMLを解析する方法