duckduckgo.py 5.3 KB

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