LoginSignup
9
10

More than 3 years have passed since last update.

Node.jsからGoogle検索を利用する

Last updated at Posted at 2019-09-10

はじめに

この記事では
Node.jsのgoogleapisというモジュールを利用して
Node.jsのjsファイルから、Google検索を行います。

今行っている研究で、Node.js上からGoogleの検索結果を取得する必要があるため、その方法をまとめます。

例えば

卯月コウと検索すると

スクリーンショット 2019-09-10 15.23.46.png

「卯月コウ-YouTube」
「卯月コウ-Twiiter」
など各要素の取得をjs上で行うことを目指します。

手順1 GoogleAPIに登録する

jsファイル上からGoogleで検索を行うにはCustom Search APIに登録する必要があります。

登録手順はCustom Search APIを使ってGoogle検索結果を取得するがわかりやすく

「検索結果を取得するまで」の 「3.Custom Search Engineの取得」まで行ってください。

手順2 ライブラリのダウンロード

GoogleがNode.js用にnpmライブラリを公開しているためダウンロードします。

npm install googleapis

でダウンロードできます。

手順3 ライブラリの利用

jsファイルから以下のように利用します。

まず、googleapisから必要なcustomSearchを取り出します。

const {google} = require('googleapis');
const customSearch = google.customsearch("v1");

次にキーワード検索を実際に行います。


const {google} = require('googleapis');
const customSearch = google.customsearch("v1");

//非同期処理
async function search_keyword(event) {

    //htmlからキーワードを取ってくる
    let keyword = document.getElementById("search_keyword_input").value;
    if (!keyword) return;

    //非同期処理なので実行終了まで待つ
    let result = await customSearch.cse.list({

        //APIキー
        auth: "APIキー https://qiita.com/zak_y/items/42ca0f1ea14f7046108cの1.APIキーの取得",

        //カスタムエンジン名ID
        cx: "エンジンID https://qiita.com/zak_y/items/42ca0f1ea14f7046108cの3.CSEの取得の検索エンジンID クリップボードにコピー",

        //検索したいキーワード
        q: keyword
    });

    //結果表示
    console.log(result);
}

customSearch.cse.list関数にパラメータを入力するのですが
名前がかなり分かりづらいです。

そもそもGoogleの検索をDevToolsで見ると分かるのですが多くのクラスがg, qなど一文字で表されています。
これは、おそらく大量のレスポンスを返すために可能な限り文字数を減らしており、その結果パラメータもものすごく単純に合わしているんだろうと思います。

卯月コウと、上記のjsファイルのkeywordに入れると
コンソールでは以下のように表示されます。

スクリーンショット 2019-09-10 15.40.02.png

参考文献いっぞ!

9
10
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10