.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
searx.engines.qwant Namespace Reference

Functions

 request (query, params)
 
 response (resp)
 
 parse_web_lite (resp)
 
 parse_web_api (resp)
 
 fetch_traits (EngineTraits engine_traits)
 

Variables

dict about
 
list categories = []
 
bool paging = True
 
int max_page = 5
 
 qwant_categ = None
 
bool safesearch = True
 
list qwant_news_locales
 
str api_url = 'https://api.qwant.com/v3/search/'
 
str web_lite_url = 'https://lite.qwant.com/'
 

Detailed Description

This engine uses the Qwant API (https://api.qwant.com/v3) to implement Qwant
-Web, -News, -Images and -Videos.  The API is undocumented but can be reverse
engineered by reading the network log of https://www.qwant.com/ queries.

For Qwant's *web-search* two alternatives are implemented:

- ``web``: uses the :py:obj:`api_url` which returns a JSON structure
- ``web-lite``: uses the :py:obj:`web_lite_url` which returns a HTML page


Configuration
=============

The engine has the following additional settings:

- :py:obj:`qwant_categ`

This implementation is used by different qwant engines in the :ref:`settings.yml
<settings engine>`:

.. code:: yaml

  - name: qwant
    qwant_categ: web-lite  # alternatively use 'web'
    ...
  - name: qwant news
    qwant_categ: news
    ...
  - name: qwant images
    qwant_categ: images
    ...
  - name: qwant videos
    qwant_categ: videos
    ...

Implementations
===============

Function Documentation

◆ fetch_traits()

searx.engines.qwant.fetch_traits ( EngineTraits engine_traits)

Definition at line 318 of file qwant.py.

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

References searx.format.

◆ parse_web_api()

searx.engines.qwant.parse_web_api ( resp)
Parse results from Qwant's API

Definition at line 180 of file qwant.py.

180def parse_web_api(resp):
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:
194 raise SearxEngineTooManyRequestsException()
195 if search_results.get("data", {}).get("error_data", {}).get("captchaUrl") is not None:
196 raise SearxEngineCaptchaException()
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

Referenced by searx.engines.qwant.response().

+ Here is the caller graph for this function:

◆ parse_web_lite()

searx.engines.qwant.parse_web_lite ( resp)
Parse results from Qwant-Lite

Definition at line 159 of file qwant.py.

159def parse_web_lite(resp):
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

Referenced by searx.engines.qwant.response().

+ Here is the caller graph for this function:

◆ request()

searx.engines.qwant.request ( query,
params )
Qwant search request

Definition at line 111 of file qwant.py.

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

◆ response()

searx.engines.qwant.response ( resp)

Definition at line 152 of file qwant.py.

152def response(resp):
153
154 if qwant_categ == 'web-lite':
155 return parse_web_lite(resp)
156 return parse_web_api(resp)
157
158

References searx.engines.qwant.parse_web_api(), and searx.engines.qwant.parse_web_lite().

+ Here is the call graph for this function:

Variable Documentation

◆ about

dict searx.engines.qwant.about
Initial value:
1= {
2 "website": 'https://www.qwant.com/',
3 "wikidata_id": 'Q14657870',
4 "official_api_documentation": None,
5 "use_official_api": True,
6 "require_api_key": False,
7 "results": 'JSON',
8}

Definition at line 70 of file qwant.py.

◆ api_url

str searx.engines.qwant.api_url = 'https://api.qwant.com/v3/search/'

Definition at line 104 of file qwant.py.

◆ categories

list searx.engines.qwant.categories = []

Definition at line 80 of file qwant.py.

◆ max_page

int searx.engines.qwant.max_page = 5

Definition at line 82 of file qwant.py.

◆ paging

bool searx.engines.qwant.paging = True

Definition at line 81 of file qwant.py.

◆ qwant_categ

searx.engines.qwant.qwant_categ = None

Definition at line 86 of file qwant.py.

◆ qwant_news_locales

list searx.engines.qwant.qwant_news_locales
Initial value:
1= [
2 'ca_ad', 'ca_es', 'ca_fr', 'co_fr', 'de_at', 'de_ch', 'de_de', 'en_au',
3 'en_ca', 'en_gb', 'en_ie', 'en_my', 'en_nz', 'en_us', 'es_ad', 'es_ar',
4 'es_cl', 'es_co', 'es_es', 'es_mx', 'es_pe', 'eu_es', 'eu_fr', 'fc_ca',
5 'fr_ad', 'fr_be', 'fr_ca', 'fr_ch', 'fr_fr', 'it_ch', 'it_it', 'nl_be',
6 'nl_nl', 'pt_ad', 'pt_pt',
7]

Definition at line 93 of file qwant.py.

◆ safesearch

bool searx.engines.qwant.safesearch = True

Definition at line 89 of file qwant.py.

◆ web_lite_url

str searx.engines.qwant.web_lite_url = 'https://lite.qwant.com/'

Definition at line 107 of file qwant.py.