.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

EngineTraits traits
 
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 310 of file qwant.py.

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

References searx.format.

◆ parse_web_api()

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

Definition at line 175 of file qwant.py.

175def parse_web_api(resp):
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:
189 raise SearxEngineTooManyRequestsException()
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

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

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

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

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

◆ response()

searx.engines.qwant.response ( resp)

Definition at line 147 of file qwant.py.

147def response(resp):
148
149 if qwant_categ == 'web-lite':
150 return parse_web_lite(resp)
151 return parse_web_api(resp)
152
153

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

◆ api_url

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

Definition at line 99 of file qwant.py.

◆ categories

list searx.engines.qwant.categories = []

Definition at line 75 of file qwant.py.

◆ max_page

int searx.engines.qwant.max_page = 5

Definition at line 77 of file qwant.py.

◆ paging

bool searx.engines.qwant.paging = True

Definition at line 76 of file qwant.py.

◆ qwant_categ

searx.engines.qwant.qwant_categ = None

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

◆ safesearch

bool searx.engines.qwant.safesearch = True

Definition at line 84 of file qwant.py.

◆ traits

EngineTraits searx.engines.qwant.traits

Definition at line 62 of file qwant.py.

◆ web_lite_url

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

Definition at line 102 of file qwant.py.