GoでGoogle Custom Search APIを利用して画像収集
Google Custom Search を利用し、Goで画像を収集。 google-api-custom-search-example を参考に実装。
前提
- (google-api-go-client)https://github.com/google/google-api-go-client/tree/master/customsearch/v1 を利用
- サービスアカウントキーを発行
構成
customsearch/ ├── customsearch.go └── search-key.json
ソース
(Google Custom Search APIを使って画像収集)http://qiita.com/onlyzs/items/c56fb76ce43e45c12339を参考に、検索エンジンID、サービスアカウントキーを発行。
search-key.json
{ "type": "xxx", "project_id": "xxx", "private_key_id": "xxx", "private_key": "-----BEGIN PRIVATE KEY-----\nxxxxx\n-----END PRIVATE KEY-----\n", "client_email": "xxx", "client_id": "xxx", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "xxx" }
customsearch.go
package main import ( "fmt" "golang.org/x/oauth2" "golang.org/x/oauth2/google" customsearch "google.golang.org/api/customsearch/v1" "io/ioutil" "log" ) func main() { data, err := ioutil.ReadFile("search-key.json") if err != nil { log.Fatal(err) } conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/cse") if err != nil { log.Fatal(err) } client := conf.Client(oauth2.NoContext) cseService, err := customsearch.New(client) search := cseService.Cse.List("ロゴ") // 検索エンジンIDを適宜設定 search.Cx("xxxxx") // Custom Search Engineで「画像検索」をオンにする search.SearchType("image") search.Start(1) call, err := search.Do() if err != nil { log.Fatal(err) } for index, r := range call.Items { fmt.Println(index) fmt.Println(r.Link) } }
実行
$ go run customsearch.go 0 https://www.google.com/cloud/assets/press/Android_Logo.png 1 https://www.google.com/cloud/assets/press/Chrome_Logo.png 2 https://www.google.com/intl/ja_ALL/insidesearch/images/promos/playground-doodles.jpg 3 https://www.google.com/cloud/assets/press/Google_Cloud_Platform_Logo.png 4 https://www.google.com/cloud/assets/press/G_Suite_Logo.png 5 https://www.google.com/cloud/assets/press/Google_Cloud_Logo.png 6 https://www.google.com/intl/ja/earth/outreach/images/tutorials_screenoverlay1.jpg 7 http://www.google.com/logos/doodles/2016/new-years-day-2016-5637619880820736-hp2x.gif 8 https://www.google.com/maps/about/images/treks/gombe/partner1-logo.jpg 9 http://www.google.com/recaptcha/shared-media/logo2.gif
参考
- 作者: 松尾愛賀
- 出版社/メーカー: 翔泳社
- 発売日: 2016/04/15
- メディア: 単行本(ソフトカバー)
- この商品を含むブログ (5件) を見る
カスタム検索
https://cse.google.com/create/new
APIのパラメータについて
https://developers.google.com/custom-search/json-api/v1/reference/cse/list