qwant.py 11 KB

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