Advertisement
here2share

# adv_google_image_search.py -- ZZZ

Aug 7th, 2015
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. # adv_google_image_search.py -- ZZZ Tk thumbnail view with external image size referencing to be added
  2.  
  3. import json, urllib2, os, sys, re
  4.  
  5. def getImgSearchUrl(searchTerm, startPage=0):
  6.     searchTerm = searchTerm.replace(' ','%20') #simple convertion
  7.     results = ''
  8.     return 'https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q={0}&start={1}&imgsz=huge'\
  9.         .format(searchTerm, startPage)
  10.  
  11. def getUrlContent(url):
  12.     try:
  13.         f = urllib2.urlopen(url)
  14.         s = f.read()
  15.         f.close()
  16.     except Exception as e:
  17.         print >> sys.stderr, e, url
  18.         return None
  19.     return s
  20.  
  21. def downloadRessource(url, destPath='', fileName=None):
  22.     if fileName == None:
  23.         fileName = os.path.basename(url) #default filename
  24.     content = getUrlContent(url)
  25.     if content:
  26.         try:
  27.             with open(destPath+fileName, 'wb') as f:
  28.                 f.write(content)
  29.             f.close()
  30.         except: print "\n??? Unable To Download Image"
  31.  
  32. def getPics(subject, destPath='', nbPages=12):
  33.  
  34.     for pageNb in xrange(nbPages):
  35.         url = getImgSearchUrl(subject, pageNb*8)
  36.         response = getUrlContent(url)
  37.         if response:
  38.             try: # Skip if 404
  39.                 jsonInfo = json.loads(response)
  40.                 results = jsonInfo['responseData']['results']
  41.                
  42.                 for res in results:
  43.                     #print res['titleNoFormatting']
  44.                     #print res['contentNoFormatting']
  45.                     print '\n>>>>>', res['width'], res['height']
  46.                     urlres = re.findall('''\S+\.jpe?g''',res['url'])[0]
  47.                     print urlres
  48.                     #downloadRessource(res['url'], destPath)
  49.             except: print "\n??? Unable To Retrieve URL Data"
  50.  
  51. getPics('Sexy Adult Wonder Woman costume -kids -children -men -boys -shirt')
  52. getPics('top 10 3D car wallpapers')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement