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