qwant.py 10 KB

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