google_images.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. search_url = 'https://www.google.com/search'\
  19. '?{query}'\
  20. '&tbm=isch'\
  21. '&ijn=1'\
  22. '&start={offset}'
  23. time_range_search = "&tbs=qdr:{range}"
  24. time_range_dict = {'day': 'd',
  25. 'week': 'w',
  26. 'month': 'm'}
  27. # do search-request
  28. def request(query, params):
  29. offset = (params['pageno'] - 1) * 100
  30. params['url'] = search_url.format(query=urlencode({'q': query}),
  31. offset=offset,
  32. safesearch=safesearch)
  33. if params['time_range'] in time_range_dict:
  34. params['url'] += time_range_search.format(range=time_range_dict[params['time_range']])
  35. if safesearch and params['safesearch']:
  36. params['url'] += '&' + urlencode({'safe': 'active'})
  37. return params
  38. # get response from search-request
  39. def response(resp):
  40. results = []
  41. dom = html.fromstring(resp.text)
  42. # parse results
  43. for result in dom.xpath('//div[@data-ved]'):
  44. metadata = loads(result.xpath('./div[@class="rg_meta"]/text()')[0])
  45. thumbnail_src = metadata['tu']
  46. # http to https
  47. thumbnail_src = thumbnail_src.replace("http://", "https://")
  48. # append result
  49. results.append({'url': metadata['ru'],
  50. 'title': metadata['pt'],
  51. 'content': metadata['s'],
  52. 'thumbnail_src': thumbnail_src,
  53. 'img_src': metadata['ou'],
  54. 'template': 'images.html'})
  55. # return results
  56. return results