Rubyでnokogiriを使って楽天商品ページの情報取得

Rubyを勉強がてら、
買い物行った時に最安値をパパッと調べるツールが欲しくて、作成中です。

目的

商品の最安値を検索して、買い物を便利にする。

開発環境

cloud9を使用。
無料で使えて、環境も複製できるので、間違っても大丈夫という安心感でやりたい放題やってます。

インストール

gem install nokogiri

実装

ruby

class ScrapeController < ApplicationController
  require 'nokogiri'
  require 'open-uri'
  require 'csv'
  require 'uri'
  
  def shop
    @items = []
    infos = {}
    opt = {}
    opt['User-Agent'] = 'Mozilla/5.0 (X11; CrOS x86_64 7520.63.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36'    
    if params[:keyword] then
      url_rakuten = 'https://search.rakuten.co.jp/search/mall/' + params[:keyword] + '/' + params[:category]
      url = URI.escape(url_rakuten)      
      charset = nil
      html = open(url, opt) do |f|
          charset = f.charset
          f.read
      end
      doc = Nokogiri::HTML.parse(html, nil, charset)
          doc.xpath('//div[@class="dui-card searchresultitem"]').each do |node|
          img = node.css('.image a img').attribute('src').value
          infos["img"] = img.split("?")[0]
          infos["href"] = node.css('.title a').attribute('href').value
          infos["title"] = node.css('.title a').inner_text
          infos["price"] = node.css('.price .important').inner_text
          @items.push(infos.clone)
      end
    end
  end
end

html

<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                <thead>
                  <tr>
                    <th>No.</th>
                    <th>画像</th>
                    <th>商品名</th>
                    <th>価格</th>
                  </tr>
                </thead>
                <tfoot>
                  <tr>
                    <th>No.</th>
                    <th>画像</th>
                    <th>商品名</th>
                    <th>価格</th>
                  </tr>
                </tfoot>
                <tbody>
                  <% @items.each do |item| %>
                    <tr>
                      <% i = 0 %>
                      <% infos = [] %>
                      <% item.each do |key, val| infos.push(val) end%>
                      <td><%= i %></td><% i += 1 %>
                      <td><img src="<%= infos[0] %>?fitin=60:60"></td>
                      <td><a href="<%= infos[1] %>" target="_blank"><%= infos[2] %></a></td>
                      <td><%= infos[3] %></td>
                    </tr>
                  <% end %>
                </tbody>
              </table>

実行結果

f:id:takoyarosan:20180724233805p:plain

今後の課題

パース?表示速度が遅いので改善しようと思います。
あと503エラーも出るので、ユーザーエージェントの偽装についても調べてみようかと。

まとめ

nokogiriを使うと簡単に情報取得できる。
503エラー、速度改善の問題がある!

追記

こんなことせんでも、楽天APIがある!!!!!!
車輪の再発明禁止!