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