duckduckgo.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """DuckDuckGo Lite
  4. """
  5. from json import loads
  6. from lxml.html import fromstring
  7. from searx.utils import (
  8. dict_subset,
  9. eval_xpath,
  10. eval_xpath_getindex,
  11. extract_text,
  12. match_language,
  13. )
  14. from searx.network import get
  15. # about
  16. about = {
  17. "website": 'https://lite.duckduckgo.com/lite',
  18. "wikidata_id": 'Q12805',
  19. "official_api_documentation": 'https://duckduckgo.com/api',
  20. "use_official_api": False,
  21. "require_api_key": False,
  22. "results": 'HTML',
  23. }
  24. # engine dependent config
  25. categories = ['general']
  26. paging = True
  27. supported_languages_url = 'https://duckduckgo.com/util/u588.js'
  28. time_range_support = True
  29. language_aliases = {
  30. 'ar-SA': 'ar-XA',
  31. 'es-419': 'es-XL',
  32. 'ja': 'jp-JP',
  33. 'ko': 'kr-KR',
  34. 'sl-SI': 'sl-SL',
  35. 'zh-TW': 'tzh-TW',
  36. 'zh-HK': 'tzh-HK',
  37. }
  38. time_range_dict = {'day': 'd', 'week': 'w', 'month': 'm', 'year': 'y'}
  39. # search-url
  40. url = 'https://lite.duckduckgo.com/lite'
  41. url_ping = 'https://duckduckgo.com/t/sl_l'
  42. # match query's language to a region code that duckduckgo will accept
  43. def get_region_code(lang, lang_list=None):
  44. if lang == 'all':
  45. return None
  46. lang_code = match_language(lang, lang_list or [], language_aliases, 'wt-WT')
  47. lang_parts = lang_code.split('-')
  48. # country code goes first
  49. return lang_parts[1].lower() + '-' + lang_parts[0].lower()
  50. def request(query, params):
  51. params['url'] = url
  52. params['method'] = 'POST'
  53. params['data']['q'] = query
  54. # The API is not documented, so we do some reverse engineering and emulate
  55. # what https://lite.duckduckgo.com/lite/ does when you press "next Page"
  56. # link again and again ..
  57. params['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
  58. # initial page does not have an offset
  59. if params['pageno'] == 2:
  60. # second page does have an offset of 30
  61. offset = (params['pageno'] - 1) * 30
  62. params['data']['s'] = offset
  63. params['data']['dc'] = offset + 1
  64. elif params['pageno'] > 2:
  65. # third and following pages do have an offset of 30 + n*50
  66. offset = 30 + (params['pageno'] - 2) * 50
  67. params['data']['s'] = offset
  68. params['data']['dc'] = offset + 1
  69. # initial page does not have additional data in the input form
  70. if params['pageno'] > 1:
  71. # request the second page (and more pages) needs 'o' and 'api' arguments
  72. params['data']['o'] = 'json'
  73. params['data']['api'] = 'd.js'
  74. # initial page does not have additional data in the input form
  75. if params['pageno'] > 2:
  76. # request the third page (and more pages) some more arguments
  77. params['data']['nextParams'] = ''
  78. params['data']['v'] = ''
  79. params['data']['vqd'] = ''
  80. region_code = get_region_code(params['language'], supported_languages)
  81. if region_code:
  82. params['data']['kl'] = region_code
  83. params['cookies']['kl'] = region_code
  84. params['data']['df'] = ''
  85. if params['time_range'] in time_range_dict:
  86. params['data']['df'] = time_range_dict[params['time_range']]
  87. params['cookies']['df'] = time_range_dict[params['time_range']]
  88. logger.debug("param data: %s", params['data'])
  89. logger.debug("param cookies: %s", params['cookies'])
  90. return params
  91. # get response from search-request
  92. def response(resp):
  93. headers_ping = dict_subset(resp.request.headers, ['User-Agent', 'Accept-Encoding', 'Accept', 'Cookie'])
  94. get(url_ping, headers=headers_ping)
  95. if resp.status_code == 303:
  96. return []
  97. results = []
  98. doc = fromstring(resp.text)
  99. result_table = eval_xpath(doc, '//html/body/form/div[@class="filters"]/table')
  100. if not len(result_table) >= 3:
  101. # no more results
  102. return []
  103. result_table = result_table[2]
  104. tr_rows = eval_xpath(result_table, './/tr')
  105. # In the last <tr> is the form of the 'previous/next page' links
  106. tr_rows = tr_rows[:-1]
  107. len_tr_rows = len(tr_rows)
  108. offset = 0
  109. while len_tr_rows >= offset + 4:
  110. # assemble table rows we need to scrap
  111. tr_title = tr_rows[offset]
  112. tr_content = tr_rows[offset + 1]
  113. offset += 4
  114. # ignore sponsored Adds <tr class="result-sponsored">
  115. if tr_content.get('class') == 'result-sponsored':
  116. continue
  117. a_tag = eval_xpath_getindex(tr_title, './/td//a[@class="result-link"]', 0, None)
  118. if a_tag is None:
  119. continue
  120. td_content = eval_xpath_getindex(tr_content, './/td[@class="result-snippet"]', 0, None)
  121. if td_content is None:
  122. continue
  123. results.append(
  124. {
  125. 'title': a_tag.text_content(),
  126. 'content': extract_text(td_content),
  127. 'url': a_tag.get('href'),
  128. }
  129. )
  130. return results
  131. # get supported languages from their site
  132. def _fetch_supported_languages(resp):
  133. # response is a js file with regions as an embedded object
  134. response_page = resp.text
  135. response_page = response_page[response_page.find('regions:{') + 8 :]
  136. response_page = response_page[: response_page.find('}') + 1]
  137. regions_json = loads(response_page)
  138. supported_languages = map((lambda x: x[3:] + '-' + x[:2].upper()), regions_json.keys())
  139. return list(supported_languages)