google_images.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """
  2. Google (Images)
  3. @website https://www.google.com
  4. @provide-api yes (https://developers.google.com/custom-search/)
  5. @using-api no
  6. @results HTML chunks with JSON inside
  7. @stable no
  8. @parse url, title, img_src
  9. """
  10. from urllib import urlencode
  11. from json import loads
  12. from lxml import html
  13. # engine dependent config
  14. categories = ['images']
  15. paging = True
  16. safesearch = True
  17. time_range_support = True
  18. number_of_results = 100
  19. search_url = 'https://www.google.com/search'\
  20. '?{query}'\
  21. '&asearch=ichunk'\
  22. '&async=_id:rg_s,_pms:s'\
  23. '&tbm=isch'\
  24. '&yv=2'\
  25. '&{search_options}'
  26. time_range_attr = "qdr:{range}"
  27. time_range_dict = {'day': 'd',
  28. 'week': 'w',
  29. 'month': 'm'}
  30. # do search-request
  31. def request(query, params):
  32. search_options = {
  33. 'ijn': params['pageno'] - 1,
  34. 'start': (params['pageno'] - 1) * number_of_results
  35. }
  36. if params['time_range'] in time_range_dict:
  37. search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']])
  38. if safesearch and params['safesearch']:
  39. search_options['safe'] = 'on'
  40. params['url'] = search_url.format(query=urlencode({'q': query}),
  41. search_options=urlencode(search_options))
  42. return params
  43. # get response from search-request
  44. def response(resp):
  45. results = []
  46. g_result = loads(resp.text)
  47. dom = html.fromstring(g_result[1][1])
  48. # parse results
  49. for result in dom.xpath('//div[@data-ved]'):
  50. try:
  51. metadata = loads(''.join(result.xpath('./div[@class="rg_meta"]/text()')))
  52. except:
  53. continue
  54. thumbnail_src = metadata['tu']
  55. # http to https
  56. thumbnail_src = thumbnail_src.replace("http://", "https://")
  57. # append result
  58. results.append({'url': metadata['ru'],
  59. 'title': metadata['pt'],
  60. 'content': metadata['s'],
  61. 'thumbnail_src': thumbnail_src,
  62. 'img_src': metadata['ou'],
  63. 'template': 'images.html'})
  64. # return results
  65. return results