I want to get images related to search words from Flickr.
--Create a Flickr account and get an API key.
--python 2.7.x series
Requirement
pip install poster
I also posted it on 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) #Number of image URLs to get
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
#Get results in JSON format
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 list
template_url = 'https://farm%s.staticflickr.com/%s/%s_%s.jpg' #URL template
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) #Add image URL to list
return url_list
if __name__ == '__main__':
API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXXX'
query = sys.argv[1]
#API KEY,Query,Pass the number of acquired images
url_list = getImageUrlFromFlickr(API_KEY, query, 10)
#Display the acquired image URL
for url in url_list:
print url
>python getImageFromFlickr.py sushi
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
Recommended Posts