.oO SearXNG Developer Documentation Oo.
Loading...
Searching...
No Matches
duckduckgo.py
Go to the documentation of this file.
1# SPDX-License-Identifier: AGPL-3.0-or-later
2"""
3DuckDuckGo WEB
4~~~~~~~~~~~~~~
5"""
6
7import json
8import re
9
10from urllib.parse import quote_plus
11
12import babel
13import lxml.html
14
15from searx import (
16 locales,
17 external_bang,
18)
19from searx.utils import (
20 eval_xpath,
21 eval_xpath_getindex,
22 extr,
23 extract_text,
24)
25from searx.network import get # see https://github.com/searxng/searxng/issues/762
26from searx.enginelib.traits import EngineTraits
27from searx.enginelib import EngineCache
28from searx.exceptions import SearxEngineCaptchaException
29from searx.result_types import EngineResults
30
31about = {
32 "website": 'https://lite.duckduckgo.com/lite/',
33 "wikidata_id": 'Q12805',
34 "use_official_api": False,
35 "require_api_key": False,
36 "results": 'HTML',
37}
38
39send_accept_language_header = True
40"""DuckDuckGo-Lite tries to guess user's preferred language from the HTTP
41``Accept-Language``. Optional the user can select a region filter (but not a
42language).
43"""
44
45# engine dependent config
46categories = ['general', 'web']
47paging = True
48time_range_support = True
49safesearch = True # user can't select but the results are filtered
50
51url = "https://html.duckduckgo.com/html/"
52
53time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'}
54form_data = {'v': 'l', 'api': 'd.js', 'o': 'json'}
55
56_CACHE: EngineCache = None # type: ignore
57"""Persistent (SQLite) key/value cache that deletes its values after ``expire``
58seconds."""
59
60
62 global _CACHE # pylint: disable=global-statement
63 if _CACHE is None:
64 _CACHE = EngineCache("duckduckgo") # type:ignore
65 return _CACHE
66
67
68def get_vqd(query: str, region: str, force_request: bool = False) -> str:
69 """Returns the ``vqd`` that fits to the *query*.
70
71 :param query: The query term
72 :param region: DDG's region code
73 :param force_request: force a request to get a vqd value from DDG
74
75 TL;DR; the ``vqd`` value is needed to pass DDG's bot protection and is used
76 by all request to DDG:
77
78 - DuckDuckGo Lite: ``https://lite.duckduckgo.com/lite`` (POST form data)
79 - DuckDuckGo Web: ``https://links.duckduckgo.com/d.js?q=...&vqd=...``
80 - DuckDuckGo Images: ``https://duckduckgo.com/i.js??q=...&vqd=...``
81 - DuckDuckGo Videos: ``https://duckduckgo.com/v.js??q=...&vqd=...``
82 - DuckDuckGo News: ``https://duckduckgo.com/news.js??q=...&vqd=...``
83
84 DDG's bot detection is sensitive to the ``vqd`` value. For some search terms
85 (such as extremely long search terms that are often sent by bots), no ``vqd``
86 value can be determined.
87
88 If SearXNG cannot determine a ``vqd`` value, then no request should go out
89 to DDG.
90
91 .. attention::
92
93 A request with a wrong ``vqd`` value leads to DDG temporarily putting
94 SearXNG's IP on a block list.
95
96 Requests from IPs in this block list run into timeouts. Not sure, but it
97 seems the block list is a sliding window: to get my IP rid from the bot list
98 I had to cool down my IP for 1h (send no requests from that IP to DDG).
99 """
100 cache = get_cache()
101 key = cache.secret_hash(f"{query}//{region}")
102 value = cache.get(key=key)
103 if value is not None and not force_request:
104 logger.debug("vqd: re-use cached value: %s", value)
105 return value
106
107 logger.debug("vqd: request value from from duckduckgo.com")
108 resp = get(f'https://duckduckgo.com/?q={quote_plus(query)}')
109 if resp.status_code == 200: # type: ignore
110 value = extr(resp.text, 'vqd="', '"') # type: ignore
111 if value:
112 logger.debug("vqd value from duckduckgo.com request: '%s'", value)
113 else:
114 logger.error("vqd: can't parse value from ddg response (return empty string)")
115 return ""
116 else:
117 logger.error("vqd: got HTTP %s from duckduckgo.com", resp.status_code)
118
119 if value:
120 cache.set(key=key, value=value)
121 else:
122 logger.error("none vqd value from duckduckgo.com: HTTP %s", resp.status_code)
123 return value
124
125
126def set_vqd(query: str, region: str, value: str):
127 cache = get_cache()
128 key = cache.secret_hash(f"{query}//{region}")
129 cache.set(key=key, value=value, expire=3600)
130
131
132def get_ddg_lang(eng_traits: EngineTraits, sxng_locale, default='en_US'):
133 """Get DuckDuckGo's language identifier from SearXNG's locale.
134
135 DuckDuckGo defines its languages by region codes (see
136 :py:obj:`fetch_traits`).
137
138 To get region and language of a DDG service use:
139
140 .. code: python
141
142 eng_region = traits.get_region(params['searxng_locale'], traits.all_locale)
143 eng_lang = get_ddg_lang(traits, params['searxng_locale'])
144
145 It might confuse, but the ``l`` value of the cookie is what SearXNG calls
146 the *region*:
147
148 .. code:: python
149
150 # !ddi paris :es-AR --> {'ad': 'es_AR', 'ah': 'ar-es', 'l': 'ar-es'}
151 params['cookies']['ad'] = eng_lang
152 params['cookies']['ah'] = eng_region
153 params['cookies']['l'] = eng_region
154
155 .. hint::
156
157 `DDG-lite <https://lite.duckduckgo.com/lite>`__ and the *no Javascript*
158 page https://html.duckduckgo.com/html do not offer a language selection
159 to the user, only a region can be selected by the user (``eng_region``
160 from the example above). DDG-lite and *no Javascript* store the selected
161 region in a cookie::
162
163 params['cookies']['kl'] = eng_region # 'ar-es'
164
165 """
166 return eng_traits.custom['lang_region'].get( # type: ignore
167 sxng_locale, eng_traits.get_language(sxng_locale, default)
168 )
169
170
171ddg_reg_map = {
172 'tw-tzh': 'zh_TW',
173 'hk-tzh': 'zh_HK',
174 'ct-ca': 'skip', # ct-ca and es-ca both map to ca_ES
175 'es-ca': 'ca_ES',
176 'id-en': 'id_ID',
177 'no-no': 'nb_NO',
178 'jp-jp': 'ja_JP',
179 'kr-kr': 'ko_KR',
180 'xa-ar': 'ar_SA',
181 'sl-sl': 'sl_SI',
182 'th-en': 'th_TH',
183 'vn-en': 'vi_VN',
184}
185
186ddg_lang_map = {
187 # use ar --> ar_EG (Egypt's arabic)
188 "ar_DZ": 'lang_region',
189 "ar_JO": 'lang_region',
190 "ar_SA": 'lang_region',
191 # use bn --> bn_BD
192 'bn_IN': 'lang_region',
193 # use de --> de_DE
194 'de_CH': 'lang_region',
195 # use en --> en_US,
196 'en_AU': 'lang_region',
197 'en_CA': 'lang_region',
198 'en_GB': 'lang_region',
199 # Esperanto
200 'eo_XX': 'eo',
201 # use es --> es_ES,
202 'es_AR': 'lang_region',
203 'es_CL': 'lang_region',
204 'es_CO': 'lang_region',
205 'es_CR': 'lang_region',
206 'es_EC': 'lang_region',
207 'es_MX': 'lang_region',
208 'es_PE': 'lang_region',
209 'es_UY': 'lang_region',
210 'es_VE': 'lang_region',
211 # use fr --> rf_FR
212 'fr_CA': 'lang_region',
213 'fr_CH': 'lang_region',
214 'fr_BE': 'lang_region',
215 # use nl --> nl_NL
216 'nl_BE': 'lang_region',
217 # use pt --> pt_PT
218 'pt_BR': 'lang_region',
219 # skip these languages
220 'od_IN': 'skip',
221 'io_XX': 'skip',
222 'tokipona_XX': 'skip',
223}
224
225
226def quote_ddg_bangs(query):
227 # quote ddg bangs
228 query_parts = []
229
230 # for val in re.split(r'(\s+)', query):
231 for val in re.split(r'(\s+)', query):
232 if not val.strip():
233 continue
234 if val.startswith('!') and external_bang.get_node(external_bang.EXTERNAL_BANGS, val[1:]):
235 val = f"'{val}'"
236 query_parts.append(val)
237 return ' '.join(query_parts)
238
239
240def request(query, params):
241 query = quote_ddg_bangs(query)
242
243 if len(query) >= 500:
244 # DDG does not accept queries with more than 499 chars
245 params["url"] = None
246 return
247
248 eng_region: str = traits.get_region(params['searxng_locale'], traits.all_locale) # type: ignore
249
250 # Note: The API is reverse-engineered from DuckDuckGo's HTML webpage
251 # (https://html.duckduckgo.com/html/) and may be subject to additional bot detection mechanisms
252 # and breaking changes in the future.
253 #
254 # The params['data'] dictionary can have the following key parameters, in this order:
255 # - q (str): Search query string
256 # - b (str): Beginning parameter - empty string for first page requests
257 # - s (int): Search offset for pagination
258 # - nextParams (str): Continuation parameters from previous page response, typically empty
259 # - v (str): Typically 'l' for subsequent pages
260 # - o (str): Output format, typically 'json'
261 # - dc (int): Display count - value equal to offset (s) + 1
262 # - api (str): API endpoint identifier, typically 'd.js'
263 # - vqd (str): Validation query digest
264 # - kl (str): Keyboard language/region code (e.g., 'en-us')
265 # - df (str): Time filter, maps to values like 'd' (day), 'w' (week), 'm' (month), 'y' (year)
266
267 params['data']['q'] = query
268
269 if params['pageno'] == 1:
270 params['data']['b'] = ""
271 elif params['pageno'] >= 2:
272 offset = 10 + (params['pageno'] - 2) * 15 # Page 2 = 10, Page 3+ = 10 + n*15
273 params['data']['s'] = offset
274 params['data']['nextParams'] = form_data.get('nextParams', '')
275 params['data']['v'] = form_data.get('v', 'l')
276 params['data']['o'] = form_data.get('o', 'json')
277 params['data']['dc'] = offset + 1
278 params['data']['api'] = form_data.get('api', 'd.js')
279
280 # vqd is required to request other pages after the first one
281 vqd = get_vqd(query, eng_region, force_request=False)
282 if vqd:
283 params['data']['vqd'] = vqd
284 else:
285 # Don't try to call follow up pages without a vqd value.
286 # DDG recognizes this as a request from a bot. This lowers the
287 # reputation of the SearXNG IP and DDG starts to activate CAPTCHAs.
288 params["url"] = None
289 return
290
291 if params['searxng_locale'].startswith("zh"):
292 # Some locales (at least China) do not have a "next page" button and DDG
293 # will return a HTTP/2 403 Forbidden for a request of such a page.
294 params["url"] = None
295 return
296
297 # Put empty kl in form data if language/region set to all
298 if eng_region == "wt-wt":
299 params['data']['kl'] = ""
300 else:
301 params['data']['kl'] = eng_region
302
303 params['data']['df'] = ''
304 if params['time_range'] in time_range_dict:
305 params['data']['df'] = time_range_dict[params['time_range']]
306 params['cookies']['df'] = time_range_dict[params['time_range']]
307
308 params['cookies']['kl'] = eng_region
309
310 params['url'] = url
311 params['method'] = 'POST'
312
313 params['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
314 params['headers']['Referer'] = url
315 params['headers']['Sec-Fetch-Dest'] = "document"
316 params['headers']['Sec-Fetch-Mode'] = "navigate" # at least this one is used by ddg's bot detection
317 params['headers']['Sec-Fetch-Site'] = "same-origin"
318 params['headers']['Sec-Fetch-User'] = "?1"
319
320 logger.debug("param headers: %s", params['headers'])
321 logger.debug("param data: %s", params['data'])
322 logger.debug("param cookies: %s", params['cookies'])
323
324
325def is_ddg_captcha(dom):
326 """In case of CAPTCHA ddg response its own *not a Robot* dialog and is not
327 redirected to a CAPTCHA page."""
328
329 return bool(eval_xpath(dom, "//form[@id='challenge-form']"))
330
331
332def response(resp) -> EngineResults:
333 results = EngineResults()
334
335 if resp.status_code == 303:
336 return results
337
338 doc = lxml.html.fromstring(resp.text)
339
340 if is_ddg_captcha(doc):
341 # set suspend time to zero is OK --> ddg does not block the IP
342 raise SearxEngineCaptchaException(suspended_time=0, message=f"CAPTCHA ({resp.search_params['data'].get('kl')})")
343
344 form = eval_xpath(doc, '//input[@name="vqd"]/..')
345 if len(form):
346 # some locales (at least China) does not have a "next page" button
347 form = form[0]
348 form_vqd = eval_xpath(form, '//input[@name="vqd"]/@value')[0]
349 set_vqd(
350 query=resp.search_params['data']['q'],
351 region=resp.search_params['data']['kl'],
352 value=str(form_vqd),
353 )
354
355 # just select "web-result" and ignore results of class "result--ad result--ad--small"
356 for div_result in eval_xpath(doc, '//div[@id="links"]/div[contains(@class, "web-result")]'):
357
358 item = {}
359 title = eval_xpath(div_result, './/h2/a')
360 if not title:
361 # this is the "No results." item in the result list
362 continue
363 item["title"] = extract_text(title)
364 item["url"] = eval_xpath(div_result, './/h2/a/@href')[0]
365 item["content"] = extract_text(
366 eval_xpath_getindex(div_result, './/a[contains(@class, "result__snippet")]', 0, [])
367 )
368 results.append(item)
369
370 zero_click_info_xpath = '//div[@id="zero_click_abstract"]'
371 zero_click = extract_text(eval_xpath(doc, zero_click_info_xpath)).strip() # type: ignore
372
373 if zero_click and (
374 "Your IP address is" not in zero_click
375 and "Your user agent:" not in zero_click
376 and "URL Decoded:" not in zero_click
377 ):
378 results.add(
379 results.types.Answer(
380 answer=zero_click,
381 url=eval_xpath_getindex(doc, '//div[@id="zero_click_abstract"]/a/@href', 0), # type: ignore
382 )
383 )
384
385 return results
386
387
388def fetch_traits(engine_traits: EngineTraits):
389 """Fetch languages & regions from DuckDuckGo.
390
391 SearXNG's ``all`` locale maps DuckDuckGo's "Alle regions" (``wt-wt``).
392 DuckDuckGo's language "Browsers preferred language" (``wt_WT``) makes no
393 sense in a SearXNG request since SearXNG's ``all`` will not add a
394 ``Accept-Language`` HTTP header. The value in ``engine_traits.all_locale``
395 is ``wt-wt`` (the region).
396
397 Beside regions DuckDuckGo also defines its languages by region codes. By
398 example these are the english languages in DuckDuckGo:
399
400 - en_US
401 - en_AU
402 - en_CA
403 - en_GB
404
405 The function :py:obj:`get_ddg_lang` evaluates DuckDuckGo's language from
406 SearXNG's locale.
407
408 """
409 # pylint: disable=too-many-branches, too-many-statements, disable=import-outside-toplevel
410 from searx.utils import js_variable_to_python
411
412 # fetch regions
413
414 engine_traits.all_locale = 'wt-wt'
415
416 # updated from u661.js to u.7669f071a13a7daa57cb / should be updated automatically?
417 resp = get('https://duckduckgo.com/dist/util/u.7669f071a13a7daa57cb.js')
418
419 if not resp.ok: # type: ignore
420 print("ERROR: response from DuckDuckGo is not OK.")
421
422 js_code = extr(resp.text, 'regions:', ',snippetLengths') # type: ignore
423
424 regions = json.loads(js_code)
425 for eng_tag, name in regions.items():
426
427 if eng_tag == 'wt-wt':
428 engine_traits.all_locale = 'wt-wt'
429 continue
430
431 region = ddg_reg_map.get(eng_tag)
432 if region == 'skip':
433 continue
434
435 if not region:
436 eng_territory, eng_lang = eng_tag.split('-')
437 region = eng_lang + '_' + eng_territory.upper()
438
439 try:
440 sxng_tag = locales.region_tag(babel.Locale.parse(region))
441 except babel.UnknownLocaleError:
442 print("ERROR: %s (%s) -> %s is unknown by babel" % (name, eng_tag, region))
443 continue
444
445 conflict = engine_traits.regions.get(sxng_tag)
446 if conflict:
447 if conflict != eng_tag:
448 print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_tag))
449 continue
450 engine_traits.regions[sxng_tag] = eng_tag
451
452 # fetch languages
453
454 engine_traits.custom['lang_region'] = {}
455
456 js_code = extr(resp.text, 'languages:', ',regions') # type: ignore
457
458 languages = js_variable_to_python(js_code)
459 for eng_lang, name in languages.items():
460
461 if eng_lang == 'wt_WT':
462 continue
463
464 babel_tag = ddg_lang_map.get(eng_lang, eng_lang)
465 if babel_tag == 'skip':
466 continue
467
468 try:
469
470 if babel_tag == 'lang_region':
471 sxng_tag = locales.region_tag(babel.Locale.parse(eng_lang))
472 engine_traits.custom['lang_region'][sxng_tag] = eng_lang
473 continue
474
475 sxng_tag = locales.language_tag(babel.Locale.parse(babel_tag))
476
477 except babel.UnknownLocaleError:
478 print("ERROR: language %s (%s) is unknown by babel" % (name, eng_lang))
479 continue
480
481 conflict = engine_traits.languages.get(sxng_tag)
482 if conflict:
483 if conflict != eng_lang:
484 print("CONFLICT: babel %s --> %s, %s" % (sxng_tag, conflict, eng_lang))
485 continue
486 engine_traits.languages[sxng_tag] = eng_lang
str get_vqd(str query, str region, bool force_request=False)
Definition duckduckgo.py:68
set_vqd(str query, str region, str value)
get_ddg_lang(EngineTraits eng_traits, sxng_locale, default='en_US')