Help us understand the problem. What is going on with this article?

PythonでGoogle Custom Search APIを使い画像収集してみた

More than 1 year has passed since last update.

Custom SearchとAPIの設定

まず、Custom SearchとAPIの設定を行うのですが、下記のURLを参考にしてみてください。
Custom Search・APIの設定

画像収集実装

images_get.py
import urllib.request
from urllib.parse import quote
import httplib2
import json 
import os
import sys
import requests

API_KEY = "" # 取得したらここに追加
CUSTOM_SEARCH_ENGINE = "" # 取得したらここに追加

# キーワードを指定してください
keywords=["犬","猫"]

# 画像を検索し、URLをimg_urlsに追加
def get_image_url(search_keywords, total_num):
    img_urls = []
    i = 0
    while i < total_num:
        query_img = "https://www.googleapis.com/customsearch/v1?key=" + API_KEY + "&cx=" + CUSTOM_SEARCH_ENGINE + "&num=" + str(10 if(total_num-i)>10 else (total_num-i)) + "&start=" + str(i+1) + "&q=" + quote(search_keywords) + "&searchType=image"
        res = urllib.request.urlopen(query_img)
        data = json.loads(res.read().decode('utf-8'))
        for j in range(len(data["items"])):
            img_urls.append(data["items"][j]["link"])
        i += 10
    return img_urls

# 画像のURLから画像を保存
def get_image(search_keywords, img_urls,j):
    for i in range(len(img_urls)):
        res = requests.get(img_urls[i])
        get_images = res.content
        filename = search_keywords + str(i) + ".jpg"
        with open(filename, 'wb') as f:
            f.write(get_images)

# 実行
for j in range(len(keywords)):
    print(keywords[j])
    img_urls = get_image_url(keywords[j],5) # キーワードごとに取得したい枚数を指定(今回は5)
    get_image(keywords[j], img_urls,j)

これを、画像を入れたいディレクトリで実行してください。
このように画像を取得できます。
犬2.jpg

画像を収集したい時に活用してください。

kagami-r0927
都内に住む大学生 機械学習/業務効率化/フロント/バックエンドに興味があります。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした