qwant.py 11 KB

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