Created
June 12, 2015 03:23
-
-
Save MasazI/807ec4f54fbdf853f4f0 to your computer and use it in GitHub Desktop.
bing_imagegetter.py
This file contains hidden or 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment