.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 engines>`:

.. 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 319 of file qwant.py.

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()

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

Definition at line 181 of file qwant.py.

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

Referenced by 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 160 of file qwant.py.

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

Referenced by response().

Here is the caller graph for this function:

◆ request()

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

Definition at line 109 of file qwant.py.

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

◆ response()

searx.engines.qwant.response ( resp)

Definition at line 153 of file qwant.py.

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

References parse_web_api(), and 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 68 of file qwant.py.

◆ api_url

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

Definition at line 102 of file qwant.py.

◆ categories

list searx.engines.qwant.categories = []

Definition at line 78 of file qwant.py.

◆ max_page

int searx.engines.qwant.max_page = 5

Definition at line 80 of file qwant.py.

◆ paging

bool searx.engines.qwant.paging = True

Definition at line 79 of file qwant.py.

◆ qwant_categ

searx.engines.qwant.qwant_categ = None

Definition at line 84 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 91 of file qwant.py.

◆ safesearch

bool searx.engines.qwant.safesearch = True

Definition at line 87 of file qwant.py.

◆ web_lite_url

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

Definition at line 105 of file qwant.py.