Google Custom Search API

  • 使い方が結構面倒
  • リクエスト回数の制限が結構ひどい。

https://developers.google.com/custom-search/ http://offsidenow.phpapps.jp/archives/415

Yahooなど他のサービスでも事情は同じらしい。

検索して、画面に表示するには以下のようなURLでGetして、結果をJSONで受け取ってパースすればよし。

home_controller.rb

# coding: utf-8
require 'uri'
require 'net/http'
class HomeController < ApplicationController

    def index
        apiKey = "ほげほげ"
        engine = "あうあう"

        #query = params[:query]
        query = "あいうえお"
        #query = "abc"

        url = "https://www.googleapis.com/customsearch/v1?key=#{apiKey}&cx=#{engine}&q=#{query}&alt=json"
        uri = URI.parse(URI.encode(url))

        http = Net::HTTP.new(uri.host, uri.port)
        http.use_ssl = true
        response = http.get(uri.request_uri)
        @result = JSON.parse(response.body)
    end
end

home/index.html.erb

<% @result["items"].each do |item|  %>
<li>
    <a href='<%= item["link"] %>' >
        <span>
            <%= item["title"] %>
        </span>
    </a>
</li>
<% end %>