Just do IT

思うは招く

Ruby + google-api-client で Custom Search JSON API を使う方法

やりたいこと

Ruby 用の google-api-client gem を使い、検索エンジンで検索ワードを指定して検索結果(順位)を取得したい。

前提

$ ruby -v
ruby 2.7.1

その他

登録方法については、以下の記事が詳しい。

APIにリクエストを送る

適当なRubyファイルをつくる。

$ touch google_search.rb
$ bundle init

(わざわざ bundler を使うまでもないかもしれないが)

gemfile

gem 'google-api-client', '~> 0.34'

インストール方法は公式ドキュメントを参照した。

googleapis/google-api-ruby-client: REST client for Google APIs

なお、Railsで使う場合は使いたいAPIを明示的にrequireしなければ動かない点に注意。

gem 'google-api-client', '~> 0.34', :require => 'google/apis/customsearch_v1'

そして、以下のコードを書いた。

require 'google/apis/customsearch_v1'

API_KEY = 'APIキーを記述'
CSE_ID = 'サーチエンジンIDを記述'

Customsearch = Google::Apis::CustomsearchV1
searcher = Customsearch::CustomsearchService.new
searcher.key = API_KEY

query = "ハンターハンター"

results = searcher.list_cses(q: query, cx: CSE_ID)
items = results.items
pp items.map {|item| { title: item.title, link: item.link} }

まずはgoogle-api-clientをインストールし、require 'google/apis/customsearch_v1'で使いたいAPIを引っ張ってくる感じ。

コードは「Rubyのgoogle-api-clientでGoogle Custom Search APIを使う - u+のブログ」を参考にさせていただいた🙏

仕様が変わったのか、イニシャライズや引数の渡し方などが変わっていたので、自分で少しの変更を加えた。

参考:Class: Google::Apis::CustomsearchV1::CustomsearchService — Documentation for google/google-api-ruby-client (master)

ハンターハンター」と検索し、タイトルとリンクが返ってきた。

[{:title=>"『HUNTER×HUNTER』(ハンター×ハンター)",
  :link=>"https://ja.wikipedia.org/wiki/HUNTER%C3%97HUNTER"},
 {:title=>"『HUNTER×HUNTER』|集英社『週刊少年ジャンプ』公式サイト",
  :link=>"https://www.shonenjump.com/j/rensai/hunter.html"},
 {:title=>"【2020最新】「ハンターハンター」キャラ強さランキングTOP20 ...",
  :link=>"https://ciatr.jp/topics/311588"},
 {:title=>"【10分でわかる】ハンターハンターの暗黒大陸編を徹底解説 ...",
  :link=>"https://www.youtube.com/watch?v=aaD1wwjWBYc"},
 {:title=>"HUNTER×HUNTER が見放題! | Hulu(フールー) 【お試し無料】",
  :link=>"https://www.hulu.jp/hunter-x-hunter"},
 {:title=>"【ハンターハンター考察】カイト徹底解説【HUNTERxHUNTER ...",
  :link=>"https://www.youtube.com/watch?v=y8Qluma0mX4"},
 {:title=>"HUNTER×HUNTER|日本テレビ",
  :link=>"https://www.ntv.co.jp/hunterhunter/sphone/"},
 {:title=>"【ハンターハンター考察】ゼノ=ゾルディック徹底解説 ...",
  :link=>"https://www.youtube.com/watch?v=Eqq1o24OFWg"},
 {:title=>"HUNTER×HUNTER|日本テレビ", :link=>"https://www.ntv.co.jp/hunterhunter/"},
 {:title=>"HUNTER X HUNTER 1 (ジャンプコミックス) | 冨樫 義博 |本 | 通販 ...",
  :link=>
   "https://www.amazon.co.jp/HUNTER-X-1-%E3%82%B8%E3%83%A3%E3%83%B3%E3%83%97%E3%82%B3%E3%83%9F%E3%83%83%E3%82%AF%E3%82%B9/dp/4088725719"}]

念のため、シークレットブラウザで「ハンターハンター」と検索して結果をチェックし、↑のデータと同じであることを確認した💪💪💪

参考