duckduckgo.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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.poolrequests 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', 'web']
  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. params['headers']['Referer'] = 'https://lite.duckduckgo.com/'
  59. # initial page does not have an offset
  60. if params['pageno'] == 2:
  61. # second page does have an offset of 30
  62. offset = (params['pageno'] - 1) * 30
  63. params['data']['s'] = offset
  64. params['data']['dc'] = offset + 1
  65. elif params['pageno'] > 2:
  66. # third and following pages do have an offset of 30 + n*50
  67. offset = 30 + (params['pageno'] - 2) * 50
  68. params['data']['s'] = offset
  69. params['data']['dc'] = offset + 1
  70. # initial page does not have additional data in the input form
  71. if params['pageno'] > 1:
  72. # request the second page (and more pages) needs 'o' and 'api' arguments
  73. params['data']['o'] = 'json'
  74. params['data']['api'] = 'd.js'
  75. # initial page does not have additional data in the input form
  76. if params['pageno'] > 2:
  77. # request the third page (and more pages) some more arguments
  78. params['data']['nextParams'] = ''
  79. params['data']['v'] = ''
  80. params['data']['vqd'] = ''
  81. region_code = get_region_code(params['language'], supported_languages)
  82. if region_code:
  83. params['data']['kl'] = region_code
  84. params['cookies']['kl'] = region_code
  85. params['data']['df'] = ''
  86. if params['time_range'] in time_range_dict:
  87. params['data']['df'] = time_range_dict[params['time_range']]
  88. params['cookies']['df'] = time_range_dict[params['time_range']]
  89. return params
  90. # get response from search-request
  91. def response(resp):
  92. headers_ping = dict_subset(resp.request.headers, ['User-Agent', 'Accept-Encoding', 'Accept', 'Cookie'])
  93. get(url_ping, headers=headers_ping)
  94. if resp.status_code == 303:
  95. return []
  96. results = []
  97. doc = fromstring(resp.text)
  98. result_table = eval_xpath(doc, '//html/body/form/div[@class="filters"]/table')
  99. if not len(result_table) >= 3:
  100. # no more results
  101. return []
  102. result_table = result_table[2]
  103. tr_rows = eval_xpath(result_table, './/tr')
  104. # In the last <tr> is the form of the 'previous/next page' links
  105. tr_rows = tr_rows[:-1]
  106. len_tr_rows = len(tr_rows)
  107. offset = 0
  108. while len_tr_rows >= offset + 4:
  109. # assemble table rows we need to scrap
  110. tr_title = tr_rows[offset]
  111. tr_content = tr_rows[offset + 1]
  112. offset += 4
  113. # ignore sponsored Adds <tr class="result-sponsored">
  114. if tr_content.get('class') == 'result-sponsored':
  115. continue
  116. a_tag = eval_xpath_getindex(tr_title, './/td//a[@class="result-link"]', 0, None)
  117. if a_tag is None:
  118. continue
  119. td_content = eval_xpath_getindex(tr_content, './/td[@class="result-snippet"]', 0, None)
  120. if td_content is None:
  121. continue
  122. results.append(
  123. {
  124. 'title': a_tag.text_content(),
  125. 'content': extract_text(td_content),
  126. 'url': a_tag.get('href'),
  127. }
  128. )
  129. return results
  130. # get supported languages from their site
  131. def _fetch_supported_languages(resp):
  132. # response is a js file with regions as an embedded object
  133. response_page = resp.text
  134. response_page = response_page[response_page.find('regions:{') + 8:]
  135. response_page = response_page[: response_page.find('}') + 1]
  136. regions_json = loads(response_page)
  137. supported_languages = map((lambda x: x[3:] + '-' + x[:2].upper()), regions_json.keys())
  138. return list(supported_languages)