#やりたいこと
Flickrから検索ワードに関連する画像を取得したい。
#事前準備
#開発環境
- python 2.7.x系
#Requirement
pip install poster
#プログラム
GitHubにも上げています。→ getImageFromFlickr.py
getImageFromFlickr.py
#coding: utf-8
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import json
import sys
import urllib2
def getImageUrlFromFlickr(API_KEY, query, N):
NUM_OF_PHOTO = str(N) #取得する画像URLの数
option = '&sort=relevance&privacy_filter=1&content_type=1&per_page='+ NUM_OF_PHOTO +'&format=json&nojsoncallback=1'
url = 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key='+ API_KEY + option
#JSON形式で結果を取得
register_openers()
datagen, headers = multipart_encode({'text': query})
request = urllib2.Request(url,datagen, headers)
response = urllib2.urlopen(request)
res_dat = response.read()
url_list = [] #URLリスト
template_url = 'https://farm%s.staticflickr.com/%s/%s_%s.jpg' #URLのテンプレート
for i in json.loads(res_dat)['photos']['photo']:
img_url = template_url % (i['farm'],i['server'],i['id'],i['secret'])
url_list.append(img_url) #リストに画像URLを追加
return url_list
if __name__ == '__main__':
API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
query = sys.argv[1]
#API KEY, クエリ, 取得した画像数を渡す
url_list = getImageUrlFromFlickr(API_KEY, query, 10)
#取得した画像URLを表示
for url in url_list:
print url
#実行結果
>python getImageFromFlickr.py 寿司
https://farm6.staticflickr.com/5043/5203889493_b5a2feacf2.jpg
https://farm5.staticflickr.com/4021/4247841124_fd2f32222e.jpg
https://farm5.staticflickr.com/4082/4801051243_b439902670.jpg
https://farm4.staticflickr.com/3384/3472202216_090d54fb52.jpg
https://farm3.staticflickr.com/2265/2505551269_78f4cb8650.jpg
https://farm6.staticflickr.com/5296/5479083865_4e6ffa9553.jpg
https://farm3.staticflickr.com/2609/4008704322_b2c9a9895f.jpg
https://farm5.staticflickr.com/4117/4801046373_3e492b224d.jpg
https://farm5.staticflickr.com/4119/4801043517_d3bf9e38b9.jpg
https://farm5.staticflickr.com/4087/5025254420_131c78cb35.jpg
#取得した画像
https://farm6.staticflickr.com/5043/5203889493_b5a2feacf2.jpg