Иногда бывает нужно набрать картинок по определённой тематике, чтобы иметь возможность выбрать из существующего набора нужную и т.д. Текущие поисковики дают такую возможность, но надо открывать браузер, переходить по страницам, работать мышкой и, вообщем, заниматься этим. Хотелось бы иметь консольную утилиту «запустил и забыл» для набора нужных картинок. Рассматривается Bing API, начало работы на Python и их связка для поиска изображений.# import used libraries
import urllib, json, sys, os, threading
def load_url(url, filename, filesystem_lock):
try:
# open connection to URL
socket = urllib.urlopen(url)
# read data
data = socket.read()
# close connection
socket.close()
# on all exceptions
except:
print "error loading", url
# if no exceptions
else:
# save loaded data
save_to_file(data, filename, filesystem_lock)
def save_to_file(data, filename, filesystem_lock):
# wait for file system and block it
filesystem_lock.acquire()
try:
# while already have file with this name
while os.path.isfile(filename):
# append '_' to the beginning of file name
filename = os.path.dirname(filename) + "/_" + os.path.basename(filename)
# open for binary writing
with open(filename, 'wb') as f:
# and save data
f.write(data)
f.close()
print filename
except:
print "error saving", filename
# release file system
filesystem_lock.release()
def main():
# Bing search URL
SERVICE_URL = "http://api.search.live.net/json.aspx"
# request parameters dictionary (will append to SERVICE_URL)
params = {}
params["appid"] = "4EFC2F2CA1F9547B3C048B40C33A6A4FEF1FAF3B"
params["sources"] = "image"
params["image.count"] = 8
params["image.offset"] = 00
# try to read command line parameters
try:
params["query"] = sys.argv[1]
images_count = int(sys.argv[2])
if len(sys.argv) > 3:
params["image.filters"] = sys.argv[3]
# if have less than 2 parameters (IndexError) or
# if second parameter cannot be cast to int (ValueError)
except (IndexError, ValueError):
# print usage string
print "Bing image search tool"
print "Usage: bing.py search_str images_count [filters]"
# end exit
return 1
# make directory at current path
dir_name = "./" + params["query"] + "/"
if not os.path.isdir(dir_name):
os.mkdir(dir_name)
# list to store loading threads
loaders = []
# file system lock object
filesystem_lock = threading.Lock()
try:
# loop for images count
while(params["image.offset"] < images_count):
# combine URL string, open it and parse with JSON
response = json.load(urllib.urlopen(SERVICE_URL + "?%s" % urllib.urlencode(params)))
# extract image section
images_section = response["SearchResponse"]["Image"]
# if current search offset greater or equal to returned total files
if "Total" not in images_section or params["image.offset"] >= images_section["Total"]:
# then break search loop
break
# extract image results section
results = images_section["Results"]
# loop for results
for result in results:
# extract image URL
image_url = result["MediaUrl"]
# create new loading thread
loader = threading.Thread(\
target = load_url,\
args=(\
image_url,\
dir_name + os.path.basename(str(image_url)),\
filesystem_lock))
# start loading thread
loader.start()
# and add it to loaders list
loaders.append(loader)
# advance search offset
params["image.offset"] += 1
# break if no more images needed
if params["image.offset"] >= images_count:
break;
# on all exceptions
except:
print "error occured"
return 1
# wait for all loading threads to complete
for loader in loaders:
loader.join()
# all done
print "done"
return 0;
if __name__ == '__main__':
status = main()
sys.exit(status)
bing.py apple 1000 — найти 1000 картинок по запросу «apple».bing.py "obama" 16 "size:large style:graphics face:face" — найти 16 портретов Обамы, большого размера в стиле иллюстрации.bing.py "warhammer wallpaper" 16 "size:width:1280 size:height:1024" — найти 16 обоев по теме «warhammer», размерами 1280x1024from distutils.core import setup
import py2exe, sys, os
sys.argv.append('py2exe')
setup(
console=['bing.py'],
options = {'py2exe': {'bundle_files': 1}},
zipfile = None,
)
<code><font color="#666666">0</font></code><code>http://api.google.com</code>Только зарегистрированные пользователи могут оставлять комментарии. Войдите, пожалуйста.
комментарии (29)