qwant.py 2.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. """
  2. Qwant (Web, Images, News, Social)
  3. @website https://qwant.com/
  4. @provide-api not officially (https://api.qwant.com/api/search/)
  5. @using-api yes
  6. @results JSON
  7. @stable yes
  8. @parse url, title, content
  9. """
  10. from datetime import datetime
  11. from json import loads
  12. from urllib import urlencode
  13. from searx.utils import html_to_text
  14. # engine dependent config
  15. categories = None
  16. paging = True
  17. language_support = True
  18. category_to_keyword = {'general': 'web',
  19. 'images': 'images',
  20. 'news': 'news',
  21. 'social media': 'social'}
  22. # search-url
  23. url = 'https://api.qwant.com/api/search/{keyword}?count=10&offset={offset}&f=&{query}'
  24. # do search-request
  25. def request(query, params):
  26. offset = (params['pageno'] - 1) * 10
  27. if categories[0] and categories[0] in category_to_keyword:
  28. params['url'] = url.format(keyword=category_to_keyword[categories[0]],
  29. query=urlencode({'q': query}),
  30. offset=offset)
  31. else:
  32. params['url'] = url.format(keyword='web',
  33. query=urlencode({'q': query}),
  34. offset=offset)
  35. # add language tag if specified
  36. if params['language'] != 'all':
  37. params['url'] += '&locale=' + params['language'].replace('-', '_').lower()
  38. return params
  39. # get response from search-request
  40. def response(resp):
  41. results = []
  42. search_results = loads(resp.text)
  43. # return empty array if there are no results
  44. if 'data' not in search_results:
  45. return []
  46. data = search_results.get('data', {})
  47. res = data.get('result', {})
  48. # parse results
  49. for result in res.get('items', {}):
  50. title = html_to_text(result['title'])
  51. res_url = result['url']
  52. content = html_to_text(result['desc'])
  53. if category_to_keyword.get(categories[0], '') == 'web':
  54. results.append({'title': title,
  55. 'content': content,
  56. 'url': res_url})
  57. elif category_to_keyword.get(categories[0], '') == 'images':
  58. thumbnail_src = result['thumbnail']
  59. img_src = result['media']
  60. results.append({'template': 'images.html',
  61. 'url': res_url,
  62. 'title': title,
  63. 'content': '',
  64. 'thumbnail_src': thumbnail_src,
  65. 'img_src': img_src})
  66. elif (category_to_keyword.get(categories[0], '') == 'news' or
  67. category_to_keyword.get(categories[0], '') == 'social'):
  68. published_date = datetime.fromtimestamp(result['date'], None)
  69. results.append({'url': res_url,
  70. 'title': title,
  71. 'publishedDate': published_date,
  72. 'content': content})
  73. # return results
  74. return results