概要
Custom Search APIを使って多少ランダムな画像の検索をしてみた。
今回はGoogleAppScriptから呼び出しをする。
Custom Search APIを利用する上で気にした点
・無料枠の1日あたり100件の検索クエリを使う
・検索結果は10件なので検索の開始位置を変えてみる
1.API KeyとCSE ID(検索エンジンID)の取得
以下の記事を参考に取得
https://www.pre-practice.net/2017/12/google-custom-search-api.html
取得したCSE ID
- 画像検索はONにする
- 検索するサイト:
www.google.co.jp/imghp?hl=ja&tab=ri&ogbl
(SearchTypeで画像指定をするが念のため)
2.GoogleAppScriptに画像検索処理を実装
・プロジェクトのプロパティにAPI Keyを設定(プロパティ名:GOOGLE_API_KEY
)
・プロジェクトのプロパティにCSE IDを設定(プロパティ名:CUSTOM_ID
)
・取得開始位置(startIndex)を指定(ここでは1~10をランダムに設定する)
・取得した値(items)のlinkをランダムに指定(ここではitemsの配列番号をランダムに設定する)
function getImage(){
// プロジェクトのプロパティからGoogleのAPI KEYを取得
var apikey = PropertiesService.getScriptProperties().getProperty('GOOGLE_API_KEY');
var apiUrl = 'https://www.googleapis.com/customsearch/v1/';
var start = 1 + Math.floor(Math.random() * 10); //取得開始位置を1~10の数値の中のどれかにする
var query = '?q='+ encodeURIComponent('検索ワード'); //検索したいワードを指定
query += '&cx=' + PropertiesService.getScriptProperties().getProperty('CUSTOM_ID'); //CSE ID
query += '&key='+ apikey;
query += '&searchType=' + 'image';
query += '&start=' + start;
apiUrl = apiUrl + query;
var response = UrlFetchApp.fetch(apiUrl);
if (response.getResponseCode() !== 200) {
throw new Error('エラーのため取得できませんでした');
} else {
var res = JSON.parse(response);
var rdm = Math.floor( Math.random() * res["items"].length );
// consoleにURLを表示
console.log(res["items"][rdm]["link"]);
}
}
取得するURLはstartIndex番号と取得したitems数のランダムになるはず。