qwant.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This engine uses the Qwant API (https://api.qwant.com/v3) to implement Qwant
  3. -Web, -News, -Images and -Videos. The API is undocumented but can be reverse
  4. engineered by reading the network log of https://www.qwant.com/ queries.
  5. For Qwant's *web-search* two alternatives are implemented:
  6. - ``web``: uses the :py:obj:`api_url` which returns a JSON structure
  7. - ``web-lite``: uses the :py:obj:`web_lite_url` which returns a HTML page
  8. Configuration
  9. =============
  10. The engine has the following additional settings:
  11. - :py:obj:`qwant_categ`
  12. This implementation is used by different qwant engines in the :ref:`settings.yml
  13. <settings engine>`:
  14. .. code:: yaml
  15. - name: qwant
  16. qwant_categ: web-lite # alternatively use 'web'
  17. ...
  18. - name: qwant news
  19. qwant_categ: news
  20. ...
  21. - name: qwant images
  22. qwant_categ: images
  23. ...
  24. - name: qwant videos
  25. qwant_categ: videos
  26. ...
  27. Implementations
  28. ===============
  29. """
  30. from datetime import (
  31. datetime,
  32. timedelta,
  33. )
  34. from json import loads
  35. from urllib.parse import urlencode
  36. from flask_babel import gettext
  37. import babel
  38. import lxml
  39. from searx.exceptions import SearxEngineAPIException, SearxEngineTooManyRequestsException
  40. from searx.network import raise_for_httperror
  41. from searx.enginelib.traits import EngineTraits
  42. from searx.utils import (
  43. eval_xpath,
  44. eval_xpath_list,
  45. extract_text,
  46. )
  47. traits: EngineTraits
  48. # about
  49. about = {
  50. "website": 'https://www.qwant.com/',
  51. "wikidata_id": 'Q14657870',
  52. "official_api_documentation": None,
  53. "use_official_api": True,
  54. "require_api_key": False,
  55. "results": 'JSON',
  56. }
  57. # engine dependent config
  58. categories = []
  59. paging = True
  60. max_page = 5
  61. """5 pages maximum (``&p=5``): Trying to do more just results in an improper
  62. redirect"""
  63. qwant_categ = None
  64. """One of ``web-lite`` (or ``web``), ``news``, ``images`` or ``videos``"""
  65. safesearch = True
  66. # safe_search_map = {0: '&safesearch=0', 1: '&safesearch=1', 2: '&safesearch=2'}
  67. # fmt: off
  68. qwant_news_locales = [
  69. 'ca_ad', 'ca_es', 'ca_fr', 'co_fr', 'de_at', 'de_ch', 'de_de', 'en_au',
  70. 'en_ca', 'en_gb', 'en_ie', 'en_my', 'en_nz', 'en_us', 'es_ad', 'es_ar',
  71. 'es_cl', 'es_co', 'es_es', 'es_mx', 'es_pe', 'eu_es', 'eu_fr', 'fc_ca',
  72. 'fr_ad', 'fr_be', 'fr_ca', 'fr_ch', 'fr_fr', 'it_ch', 'it_it', 'nl_be',
  73. 'nl_nl', 'pt_ad', 'pt_pt',
  74. ]
  75. # fmt: on
  76. # search-url
  77. api_url = 'https://api.qwant.com/v3/search/'
  78. """URL of Qwant's API (JSON)"""
  79. web_lite_url = 'https://lite.qwant.com/'
  80. """URL of Qwant-Lite (HTML)"""
  81. def request(query, params):
  82. """Qwant search request"""
  83. if not query:
  84. return None
  85. q_locale = traits.get_region(params["searxng_locale"], default='en_US')
  86. url = api_url + f'{qwant_categ}?'
  87. args = {'q': query}
  88. params['raise_for_httperror'] = False
  89. if qwant_categ == 'web-lite':
  90. url = web_lite_url + '?'
  91. args['locale'] = q_locale.lower()
  92. args['l'] = q_locale.split('_')[0]
  93. args['s'] = params['safesearch']
  94. args['p'] = params['pageno']
  95. params['raise_for_httperror'] = True
  96. elif qwant_categ == 'images':
  97. args['locale'] = q_locale
  98. args['safesearch'] = params['safesearch']
  99. args['count'] = 50
  100. args['offset'] = (params['pageno'] - 1) * args['count']
  101. else: # web, news, videos
  102. args['locale'] = q_locale
  103. args['safesearch'] = params['safesearch']
  104. args['count'] = 10
  105. args['offset'] = (params['pageno'] - 1) * args['count']
  106. params['url'] = url + urlencode(args)
  107. return params
  108. def response(resp):
  109. if qwant_categ == 'web-lite':
  110. return parse_web_lite(resp)
  111. return parse_web_api(resp)
  112. def parse_web_lite(resp):
  113. """Parse results from Qwant-Lite"""
  114. results = []
  115. dom = lxml.html.fromstring(resp.text)
  116. for item in eval_xpath_list(dom, '//section/article'):
  117. if eval_xpath(item, "./span[contains(@class, 'tooltip')]"):
  118. # ignore randomly interspersed advertising adds
  119. continue
  120. results.append(
  121. {
  122. 'url': extract_text(eval_xpath(item, "./span[contains(@class, 'url partner')]")),
  123. 'title': extract_text(eval_xpath(item, './h2/a')),
  124. 'content': extract_text(eval_xpath(item, './p')),
  125. }
  126. )
  127. return results
  128. def parse_web_api(resp):
  129. """Parse results from Qwant's API"""
  130. # pylint: disable=too-many-locals, too-many-branches, too-many-statements
  131. results = []
  132. # load JSON result
  133. search_results = loads(resp.text)
  134. data = search_results.get('data', {})
  135. # check for an API error
  136. if search_results.get('status') != 'success':
  137. error_code = data.get('error_code')
  138. if error_code == 24:
  139. raise SearxEngineTooManyRequestsException()
  140. msg = ",".join(data.get('message', ['unknown']))
  141. raise SearxEngineAPIException(f"{msg} ({error_code})")
  142. # raise for other errors
  143. raise_for_httperror(resp)
  144. if qwant_categ == 'web':
  145. # The WEB query contains a list named 'mainline'. This list can contain
  146. # different result types (e.g. mainline[0]['type'] returns type of the
  147. # result items in mainline[0]['items']
  148. mainline = data.get('result', {}).get('items', {}).get('mainline', {})
  149. else:
  150. # Queries on News, Images and Videos do not have a list named 'mainline'
  151. # in the response. The result items are directly in the list
  152. # result['items'].
  153. mainline = data.get('result', {}).get('items', [])
  154. mainline = [
  155. {'type': qwant_categ, 'items': mainline},
  156. ]
  157. # return empty array if there are no results
  158. if not mainline:
  159. return []
  160. for row in mainline:
  161. mainline_type = row.get('type', 'web')
  162. if mainline_type != qwant_categ:
  163. continue
  164. if mainline_type == 'ads':
  165. # ignore adds
  166. continue
  167. mainline_items = row.get('items', [])
  168. for item in mainline_items:
  169. title = item.get('title', None)
  170. res_url = item.get('url', None)
  171. if mainline_type == 'web':
  172. content = item['desc']
  173. results.append(
  174. {
  175. 'title': title,
  176. 'url': res_url,
  177. 'content': content,
  178. }
  179. )
  180. elif mainline_type == 'news':
  181. pub_date = item['date']
  182. if pub_date is not None:
  183. pub_date = datetime.fromtimestamp(pub_date)
  184. news_media = item.get('media', [])
  185. thumbnail = None
  186. if news_media:
  187. thumbnail = news_media[0].get('pict', {}).get('url', None)
  188. results.append(
  189. {
  190. 'title': title,
  191. 'url': res_url,
  192. 'publishedDate': pub_date,
  193. 'thumbnail': thumbnail,
  194. }
  195. )
  196. elif mainline_type == 'images':
  197. thumbnail = item['thumbnail']
  198. img_src = item['media']
  199. results.append(
  200. {
  201. 'title': title,
  202. 'url': res_url,
  203. 'template': 'images.html',
  204. 'thumbnail_src': thumbnail,
  205. 'img_src': img_src,
  206. 'resolution': f"{item['width']} x {item['height']}",
  207. 'img_format': item.get('thumb_type'),
  208. }
  209. )
  210. elif mainline_type == 'videos':
  211. # some videos do not have a description: while qwant-video
  212. # returns an empty string, such video from a qwant-web query
  213. # miss the 'desc' key.
  214. d, s, c = item.get('desc'), item.get('source'), item.get('channel')
  215. content_parts = []
  216. if d:
  217. content_parts.append(d)
  218. if s:
  219. content_parts.append("%s: %s " % (gettext("Source"), s))
  220. if c:
  221. content_parts.append("%s: %s " % (gettext("Channel"), c))
  222. content = ' // '.join(content_parts)
  223. length = item['duration']
  224. if length is not None:
  225. length = timedelta(milliseconds=length)
  226. pub_date = item['date']
  227. if pub_date is not None:
  228. pub_date = datetime.fromtimestamp(pub_date)
  229. thumbnail = item['thumbnail']
  230. # from some locations (DE and others?) the s2 link do
  231. # response a 'Please wait ..' but does not deliver the thumbnail
  232. thumbnail = thumbnail.replace('https://s2.qwant.com', 'https://s1.qwant.com', 1)
  233. results.append(
  234. {
  235. 'title': title,
  236. 'url': res_url,
  237. 'content': content,
  238. 'publishedDate': pub_date,
  239. 'thumbnail': thumbnail,
  240. 'template': 'videos.html',
  241. 'length': length,
  242. }
  243. )
  244. return results
  245. def fetch_traits(engine_traits: EngineTraits):
  246. # pylint: disable=import-outside-toplevel
  247. from searx import network
  248. from searx.locales import region_tag
  249. resp = network.get(about['website'])
  250. text = resp.text
  251. text = text[text.find('INITIAL_PROPS') :]
  252. text = text[text.find('{') : text.find('</script>')]
  253. q_initial_props = loads(text)
  254. q_locales = q_initial_props.get('locales')
  255. eng_tag_list = set()
  256. for country, v in q_locales.items():
  257. for lang in v['langs']:
  258. _locale = "{lang}_{country}".format(lang=lang, country=country)
  259. if qwant_categ == 'news' and _locale.lower() not in qwant_news_locales:
  260. # qwant-news does not support all locales from qwant-web:
  261. continue
  262. eng_tag_list.add(_locale)
  263. for eng_tag in eng_tag_list:
  264. try:
  265. sxng_tag = region_tag(babel.Locale.parse(eng_tag, sep='_'))
  266. except babel.UnknownLocaleError:
  267. print("ERROR: can't determine babel locale of quant's locale %s" % eng_tag)
  268. continue
  269. conflict = engine_traits.regions.get(sxng_tag)
  270. if conflict:
  271. if conflict != eng_tag:
  272. print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
  273. continue
  274. engine_traits.regions[sxng_tag] = eng_tag