Python3でGoogle画像検索から画像ダウンロード
python3でGoogle画像検索から画像をダウンロードするスクリプトを作成してみました。
python2で書かれているものがほとんどだったのでpython3で書いてみました。(ほとんどパクリですが...)
以下のホームページを参考にさせていただきました。
美人画像をダウンロードするスクリプトを作成してみた。GeekToolのお供にどうぞ|GarageGentlemen
#! /usr/local/bin/ env python3 # -*- coding: utf-8 -*- # Download a random picture from Google image search. # import os import urllib.parse import urllib.request import json import random import imghdr import subprocess def get_image(num, word): if len(word) <= 0: print('Usage:') print('python fetch_google_image.py cat cute') exit() q = '' for arg in word: q += urllib.parse.quote(arg) + '+' f = urllib.request.urlopen('http://ajax.googleapis.com/ajax/services/search/images?q=' + q + '&v=1.0&rsz=small').read().decode('utf-8') data = json.loads(f) results = data['responseData']['results'] # url = results[random.randint(0, len(results) - 1)]['url'] # 優先順位ランダムにするならこっち url = results[0]['url'] urllib.request.urlretrieve(url, './image/tmp') imagetype = imghdr.what('./image/tmp') if not(type(imagetype) is None): filename = './image/{0:0>4}'.format(num) + '.' + imagetype os.rename('./image/tmp', filename) print("get imge num : {0}".format(num)) print("get imge name : {0}".format(word)) if __name__ == '__main__': testword = ["猫"] get_image(0, testword)
検索ワードをリストに格納しておき、画像取得関数に渡してやります。
*複数キーワードで検索したい場合はtestword = ["猫", "かわいい"]
にします。
実行結果は以下の通りです。