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