google_images.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 datetime import date, timedelta
  11. from json import loads
  12. from lxml import html
  13. from searx.url_utils import urlencode
  14. # engine dependent config
  15. categories = ['images']
  16. paging = True
  17. safesearch = True
  18. time_range_support = True
  19. number_of_results = 100
  20. search_url = 'https://www.google.com/search'\
  21. '?{query}'\
  22. '&tbm=isch'\
  23. '&yv=2'\
  24. '&{search_options}'
  25. time_range_attr = "qdr:{range}"
  26. time_range_custom_attr = "cdr:1,cd_min:{start},cd_max{end}"
  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. elif params['time_range'] == 'year':
  39. now = date.today()
  40. then = now - timedelta(days=365)
  41. start = then.strftime('%m/%d/%Y')
  42. end = now.strftime('%m/%d/%Y')
  43. search_options['tbs'] = time_range_custom_attr.format(start=start, end=end)
  44. if safesearch and params['safesearch']:
  45. search_options['safe'] = 'on'
  46. params['url'] = search_url.format(query=urlencode({'q': query}),
  47. search_options=urlencode(search_options))
  48. return params
  49. # get response from search-request
  50. def response(resp):
  51. results = []
  52. dom = html.fromstring(resp.text)
  53. # parse results
  54. for result in dom.xpath('//div[contains(@class, "rg_meta")]/text()'):
  55. try:
  56. metadata = loads(result)
  57. img_format = metadata.get('ity', '')
  58. img_width = metadata.get('ow', '')
  59. img_height = metadata.get('oh', '')
  60. if img_width and img_height:
  61. img_format += " {0}x{1}".format(img_width, img_height)
  62. source = metadata.get('st', '')
  63. source_url = metadata.get('isu', '')
  64. if source_url:
  65. source += " ({0})".format(source_url)
  66. results.append({'url': metadata['ru'],
  67. 'title': metadata['pt'],
  68. 'content': metadata.get('s', ''),
  69. 'source': source,
  70. 'img_format': img_format,
  71. 'thumbnail_src': metadata['tu'],
  72. 'img_src': metadata['ou'],
  73. 'template': 'images.html'})
  74. except:
  75. continue
  76. return results