@@ -1,15 +1,41 @@
1# SPDX-License-Identifier: AGPL-3.0-or-later
1# SPDX-License-Identifier: AGPL-3.0-or-later
3− Qwant (Web, Images, News, Social)
3+"""Qwant (Web, News, Images, Videos)
5+This engine uses the Qwant API (https://api.qwant.com/v3). The API is
6+undocumented but can be reverse engineered by reading the network log of
7+https://www.qwant.com/ queries.
9+This implementation is used by different qwant engines in the settings.yml::
6−from datetime import datetime
26+from datetime import (
7from json import loads
30from json import loads
8from urllib.parse import urlencode
31from urllib.parse import urlencode
32+from flask_babel import gettext
9−from searx.utils import html_to_text, match_language
34+from searx.utils import match_language
10−from searx.exceptions import SearxEngineAPIException, SearxEngineCaptchaException
35+from searx.exceptions import SearxEngineAPIException
11from searx.network import raise_for_httperror
36from searx.network import raise_for_httperror
15 "website": 'https://www.qwant.com/',
41 "website": 'https://www.qwant.com/',
@@ -25,98 +51,175 @@ categories = []
25paging = True
51paging = True
26supported_languages_url = about['website']
52supported_languages_url = about['website']
28−category_to_keyword = {'general': 'web',
54+category_to_keyword = {
29− 'images': 'images',
57+ 'images': 'images',
30− 'news': 'news'}
58+ 'videos': 'videos',
32# search-url
61# search-url
33−url = 'https://api.qwant.com/api/search/{keyword}?count=10&offset={offset}&f=&{query}&t={keyword}&uiv=4'
62+url = 'https://api.qwant.com/v3/search/{keyword}?q={query}&count={count}&offset={offset}'
37def request(query, params):
65def request(query, params):
66+ """Qwant search request"""
67+ keyword = category_to_keyword[categories[0]]
68+ count = 10 # web: count must be equal to 10
70+ if keyword == 'images':
38− offset = (params['pageno'] - 1) * 10
72+ offset = (params['pageno'] - 1) * count
39−
73+ # count + offset must be lower than 250
40− if categories[0] and categories[0] in category_to_keyword:
74+ offset = min(offset, 199)
42− params['url'] = url.format(keyword=category_to_keyword[categories[0]],
43− query=urlencode({'q': query}),
76+ offset = (params['pageno'] - 1) * count
77+ # count + offset must be lower than 50
78+ offset = min(offset, 40)
46− params['url'] = url.format(keyword='web',
80+ params['url'] = url.format(
47− query=urlencode({'q': query}),
82+ query=urlencode({'q': query}),
48− offset=offset)
83+ offset=offset,
50 # add language tag
87 # add language tag
51− if params['language'] != 'all':
88+ if params['language'] == 'all':
89+ params['url'] += '&locale=en_us'
52− language = match_language(params['language'], supported_languages, language_aliases)
91+ language = match_language(
93+ # pylint: disable=undefined-variable
53 params['url'] += '&locale=' + language.replace('-', '_').lower()
97 params['url'] += '&locale=' + language.replace('-', '_').lower()
55− params['headers']['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64; rv:69.0) Gecko/20100101 Firefox/69.0'
56 params['raise_for_httperror'] = False
99 params['raise_for_httperror'] = False
57 return params
100 return params
60−# get response from search-request
61def response(resp):
103def response(resp):
62− results = []
104+ """Get response from Qwant's search request"""
105+ # pylint: disable=too-many-locals, too-many-branches, too-many-statements
64− # According to https://www.qwant.com/js/app.js
107+ keyword = category_to_keyword[categories[0]]
65− if resp.status_code == 429:
108+ results = []
66− raise SearxEngineCaptchaException()
68− # raise for other errors
69− raise_for_httperror(resp)
71 # load JSON result
110 # load JSON result
72 search_results = loads(resp.text)
111 search_results = loads(resp.text)
112+ data = search_results.get('data', {})
74 # check for an API error
114 # check for an API error
75 if search_results.get('status') != 'success':
115 if search_results.get('status') != 'success':
116+ msg = ",".join(data.get('message', ['unknown', ]))
76− raise SearxEngineAPIException('API error ' + str(search_results.get('error', '')))
117+ raise SearxEngineAPIException('API error::' + msg)
119+ # raise for other errors
120+ raise_for_httperror(resp)
122+ if keyword == 'web':
123+ # The WEB query contains a list named 'mainline'. This list can contain
124+ # different result types (e.g. mainline[0]['type'] returns type of the
125+ # result items in mainline[0]['items']
126+ mainline = data.get('result', {}).get('items', {}).get('mainline', {})
128+ # Queries on News, Images and Videos do not have a list named 'mainline'
129+ # in the response. The result items are directly in the list
131+ mainline = data.get('result', {}).get('items', [])
133+ {'type': keyword, 'items': mainline},
78 # return empty array if there are no results
136 # return empty array if there are no results
79− if 'data' not in search_results:
137+ if not mainline:
80 return []
138 return []
82− data = search_results.get('data', {})
140+ for row in mainline:
142+ mainline_type = row.get('type', 'web')
143+ if mainline_type == 'ads':
147+ mainline_items = row.get('items', [])
148+ for item in mainline_items:
150+ title = item.get('title', None)
151+ res_url = item.get('url', None)
153+ if mainline_type == 'web':
154+ content = item['desc']
161+ elif mainline_type == 'news':
84− res = data.get('result', {})
163+ pub_date = item['date']
85−
164+ if pub_date is not None:
87− for result in res.get('items', {}):
89− title = html_to_text(result['title'])
90− res_url = result['url']
91− content = html_to_text(result['desc'])
93− if category_to_keyword.get(categories[0], '') == 'web':
94− results.append({'title': title,
98− elif category_to_keyword.get(categories[0], '') == 'images':
99− thumbnail_src = result['thumbnail']
100− img_src = result['media']
101− results.append({'template': 'images.html',
105− 'thumbnail_src': thumbnail_src,
106− 'img_src': img_src})
108− elif category_to_keyword.get(categories[0], '') == 'news':
109− published_date = datetime.fromtimestamp(result['date'], None)
165+ pub_date = datetime.fromtimestamp(pub_date)
110− media = result.get('media', [])
166+ news_media = item.get('media', [])
112− img_src = media[0].get('pict', {}).get('url', None)
114 img_src = None
167 img_src = None
169+ img_src = news_media[0].get('pict', {}).get('url', None)
173+ 'publishedDate': pub_date,
177+ elif mainline_type == 'images':
178+ thumbnail = item['thumbnail']
179+ img_src = item['media']
115− results.append({'url': res_url,
180+ results.append({
183+ 'template': 'images.html',
184+ 'thumbnail_src': thumbnail,
188+ elif mainline_type == 'videos':
189+ # some videos do not have a description: while qwant-video
190+ # returns an empty string, such video from a qwant-web query
191+ # miss the 'desc' key.
192+ d, s, c = item.get('desc'), item.get('source'), item.get('channel')
195+ content_parts.append(d)
197+ content_parts.append("%s: %s " % (gettext("Source"), s))
199+ content_parts.append("%s: %s " % (gettext("Channel"), c))
200+ content = ' // '.join(content_parts)
201+ length = item['duration']
202+ if length is not None:
203+ length = timedelta(milliseconds=length)
204+ pub_date = item['date']
205+ if pub_date is not None:
206+ pub_date = datetime.fromtimestamp(pub_date)
207+ thumbnail = item['thumbnail']
208+ # from some locations (DE and others?) the s2 link do
209+ # response a 'Please wait ..' but does not deliver the thumbnail
210+ thumbnail = thumbnail.replace(
211+ 'https://s2.qwant.com',
212+ 'https://s1.qwant.com', 1
116− 'title': title,
215+ 'title': title,
117− 'publishedDate': published_date,
216+ 'url': res_url,
118− 'content': content,
217+ 'content': content,
119− 'img_src': img_src})
218+ 'publishedDate': pub_date,
219+ 'thumbnail': thumbnail,
220+ 'template': 'videos.html',
121 return results
224 return results