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