google_images.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 lxml import html
  12. from searx.url_utils import urlencode, urlparse, parse_qs
  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. '&tbm=isch'\
  22. '&gbv=1'\
  23. '&sa=G'\
  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. 'start': (params['pageno'] - 1) * number_of_results
  34. }
  35. if params['time_range'] in time_range_dict:
  36. search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']])
  37. elif params['time_range'] == 'year':
  38. now = date.today()
  39. then = now - timedelta(days=365)
  40. start = then.strftime('%m/%d/%Y')
  41. end = now.strftime('%m/%d/%Y')
  42. search_options['tbs'] = time_range_custom_attr.format(start=start, end=end)
  43. if safesearch and params['safesearch']:
  44. search_options['safe'] = 'active'
  45. params['url'] = search_url.format(query=urlencode({'q': query}),
  46. search_options=urlencode(search_options))
  47. return params
  48. # get response from search-request
  49. def response(resp):
  50. dom = html.fromstring(resp.text)
  51. results = []
  52. for element in dom.xpath('//div[@id="search"] //td'):
  53. link = element.xpath('./a')[0]
  54. google_url = urlparse(link.xpath('.//@href')[0])
  55. query = parse_qs(google_url.query)
  56. source_url = next(iter(query.get('q', [])), None)
  57. title_parts = element.xpath('./cite//following-sibling::*/text()')
  58. title_parts.extend(element.xpath('./cite//following-sibling::text()')[:-1])
  59. result = {
  60. 'title': ''.join(title_parts),
  61. 'content': '',
  62. 'template': 'images.html',
  63. 'url': source_url,
  64. 'img_src': source_url,
  65. 'thumbnail_src': next(iter(link.xpath('.//img //@src')), None)
  66. }
  67. if not source_url or not result['thumbnail_src']:
  68. continue
  69. results.append(result)
  70. return results