google_images.py 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. """
  2. Google (Images)
  3. @website https://www.google.com
  4. @provide-api yes (https://developers.google.com/web-search/docs/),
  5. deprecated!
  6. @using-api yes
  7. @results JSON
  8. @stable yes (but deprecated)
  9. @parse url, title, img_src
  10. """
  11. from urllib import urlencode, unquote
  12. from json import loads
  13. # engine dependent config
  14. categories = ['images']
  15. paging = True
  16. safesearch = True
  17. # search-url
  18. url = 'https://ajax.googleapis.com/'
  19. search_url = url + 'ajax/services/search/images?v=1.0&start={offset}&rsz=large&safe={safesearch}&filter=off&{query}'
  20. # do search-request
  21. def request(query, params):
  22. offset = (params['pageno'] - 1) * 8
  23. if params['safesearch'] == 0:
  24. safesearch = 'off'
  25. else:
  26. safesearch = 'on'
  27. params['url'] = search_url.format(query=urlencode({'q': query}),
  28. offset=offset,
  29. safesearch=safesearch)
  30. return params
  31. # get response from search-request
  32. def response(resp):
  33. results = []
  34. search_res = loads(resp.text)
  35. # return empty array if there are no results
  36. if not search_res.get('responseData', {}).get('results'):
  37. return []
  38. # parse results
  39. for result in search_res['responseData']['results']:
  40. href = result['originalContextUrl']
  41. title = result['title']
  42. if 'url' not in result:
  43. continue
  44. thumbnail_src = result['tbUrl']
  45. # http to https
  46. thumbnail_src = thumbnail_src.replace("http://", "https://")
  47. # append result
  48. results.append({'url': href,
  49. 'title': title,
  50. 'content': result['content'],
  51. 'thumbnail_src': thumbnail_src,
  52. 'img_src': unquote(result['url']),
  53. 'template': 'images.html'})
  54. # return results
  55. return results