そのまま商品表示に乗せるのには大きすぎるし、出来れば星の数の部分だけ取得してきたい。
(2019/08/24追記:掲載期限が決まっているので時間が経つと表示されなくなります)
というわけで、スクレイピングです。
Laravelでスクレイピング
Laravelでスクレイピングするには「Goutte」を使うのが定番のようなので、こちらに従ってインストールします。といってもcomposerでインストールして、config/app.phpに記載するだけですが。LaravelでGoutteを利用してWebスクレイピング – Qiita
使い方はこんな感じです。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Weidner\Goutte\GoutteFacade as GoutteFacade; | |
class SampleController extends Controller | |
{ | |
public function __invoke() | |
{ | |
$goutte = GoutteFacade::request('GET',$review_url); | |
} | |
} |
これで$review_urlをスクレイピング出来ます。
星の数を取得する
星は画像で表現されているので、その画像のURLが取得出来れば十分です。取得の仕方は次の通り。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$goutte = GoutteFacade::request('GET',$review_url); | |
$star = $goutte->filter('.crAvgStars')->filter('img')->attr('src'); |
これで画像を取得出来るので、あとはそれを表示するだけ。
表示例
ね、簡単でしょ?