保存ディレクトリとか検索ワードの指定をパラメータで引き渡すようにして少し使いやすくしたつもり。収集する画像の最大枚数を指定することも可能。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#conding:utf-8 | |
import sys | |
import os | |
import urllib | |
import urllib2 | |
import json | |
import requests | |
KEY = '<Your Bing Developer Key>' | |
OUTPUT = '/images/bing/' | |
MAX = 100 | |
count = 1 | |
def bing_search(query, directory, skip): | |
global count | |
bing_url = 'https://api.datamarket.azure.com/Bing/Search/v1/Image' | |
print 'search count: ' + str(count) + ', url: ' + bing_url + ', skip: ' + str(skip) | |
pm = urllib2.HTTPPasswordMgrWithDefaultRealm() | |
pm.add_password(None, bing_url, KEY, KEY) | |
handler = urllib2.HTTPBasicAuthHandler(pm) | |
opener = urllib2.build_opener(handler) | |
urllib2.install_opener(opener) | |
if skip > 0: | |
params = urllib.urlencode({'Query': "'" + query + "'", 'Adult': "'Off'", '$skip': skip ,'$format': 'json'}) | |
else: | |
params = urllib.urlencode({'Query': "'" + query + "'", 'Adult': "'Off'", '$format': 'json'}) | |
response = urllib2.urlopen(bing_url+'?'+params) | |
data = json.loads(response.read()) | |
results = data['d']['results'] | |
for item in results: | |
if count > MAX: | |
print 'finish. count: ' + str(MAX) | |
return | |
image_url = item['MediaUrl'] | |
root,ext = os.path.splitext(image_url) | |
if ext.lower() == '.jpg': | |
print image_url, | |
try: | |
r = requests.get(image_url) | |
fname = OUTPUT + directory + "/bing%04d.jpg" % count | |
f = open(fname, 'wb') | |
f.write(r.content) | |
f.close() | |
print "...save", fname | |
except: | |
print "error", fname | |
count += 1 | |
bing_search(query, directory, count) | |
if __name__ == '__main__': | |
argvs = sys.argv | |
argc = len(argvs) | |
if(argc != 3): | |
print 'Usage: python %s query directory' % argvs[0] | |
quit() | |
query = argvs[1] | |
directory = argvs[2] | |
print 'get bing image: %s ' % query | |
bing_search(query, directory, 0) |
0 件のコメント:
コメントを投稿