duckduckgo.py 5.3 KB

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