duckduckgo.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. """
  2. DuckDuckGo (Web)
  3. @website https://duckduckgo.com/
  4. @provide-api yes (https://duckduckgo.com/api),
  5. but not all results from search-site
  6. @using-api no
  7. @results HTML (using search portal)
  8. @stable no (HTML can change)
  9. @parse url, title, content
  10. @todo rewrite to api
  11. """
  12. from lxml.html import fromstring
  13. from json import loads
  14. from searx.engines.xpath import extract_text
  15. from searx.poolrequests import get
  16. from searx.url_utils import urlencode
  17. from searx.utils import match_language, eval_xpath
  18. # engine dependent config
  19. categories = ['general']
  20. paging = True
  21. language_support = True
  22. supported_languages_url = 'https://duckduckgo.com/util/u172.js'
  23. time_range_support = True
  24. language_aliases = {
  25. 'ar-SA': 'ar-XA',
  26. 'es-419': 'es-XL',
  27. 'ja': 'jp-JP',
  28. 'ko': 'kr-KR',
  29. 'sl-SI': 'sl-SL',
  30. 'zh-TW': 'tzh-TW',
  31. 'zh-HK': 'tzh-HK'
  32. }
  33. # search-url
  34. url = 'https://duckduckgo.com/html?{query}&s={offset}&dc={dc_param}'
  35. time_range_url = '&df={range}'
  36. time_range_dict = {'day': 'd',
  37. 'week': 'w',
  38. 'month': 'm'}
  39. # specific xpath variables
  40. result_xpath = '//div[@class="result results_links results_links_deep web-result "]' # noqa
  41. url_xpath = './/a[@class="result__a"]/@href'
  42. title_xpath = './/a[@class="result__a"]'
  43. content_xpath = './/a[@class="result__snippet"]'
  44. correction_xpath = '//div[@id="did_you_mean"]//a'
  45. # match query's language to a region code that duckduckgo will accept
  46. def get_region_code(lang, lang_list=[]):
  47. if lang == 'all':
  48. return None
  49. lang_code = match_language(lang, lang_list, language_aliases, 'wt-WT')
  50. lang_parts = lang_code.split('-')
  51. # country code goes first
  52. return lang_parts[1].lower() + '-' + lang_parts[0].lower()
  53. def request(query, params):
  54. if params['time_range'] not in (None, 'None', '') and params['time_range'] not in time_range_dict:
  55. return params
  56. offset = (params['pageno'] - 1) * 30
  57. region_code = get_region_code(params['language'], supported_languages)
  58. params['url'] = 'https://duckduckgo.com/html/'
  59. if params['pageno'] > 1:
  60. params['method'] = 'POST'
  61. params['data']['q'] = query
  62. params['data']['s'] = offset
  63. params['data']['dc'] = 30
  64. params['data']['nextParams'] = ''
  65. params['data']['v'] = 'l'
  66. params['data']['o'] = 'json'
  67. params['data']['api'] = '/d.js'
  68. if params['time_range'] in time_range_dict:
  69. params['data']['df'] = time_range_dict[params['time_range']]
  70. if region_code:
  71. params['data']['kl'] = region_code
  72. else:
  73. if region_code:
  74. params['url'] = url.format(
  75. query=urlencode({'q': query, 'kl': region_code}), offset=offset, dc_param=offset)
  76. else:
  77. params['url'] = url.format(
  78. query=urlencode({'q': query}), offset=offset, dc_param=offset)
  79. if params['time_range'] in time_range_dict:
  80. params['url'] += time_range_url.format(range=time_range_dict[params['time_range']])
  81. return params
  82. # get response from search-request
  83. def response(resp):
  84. results = []
  85. doc = fromstring(resp.text)
  86. # parse results
  87. for i, r in enumerate(eval_xpath(doc, result_xpath)):
  88. if i >= 30:
  89. break
  90. try:
  91. res_url = eval_xpath(r, url_xpath)[-1]
  92. except:
  93. continue
  94. if not res_url:
  95. continue
  96. title = extract_text(eval_xpath(r, title_xpath))
  97. content = extract_text(eval_xpath(r, content_xpath))
  98. # append result
  99. results.append({'title': title,
  100. 'content': content,
  101. 'url': res_url})
  102. # parse correction
  103. for correction in eval_xpath(doc, correction_xpath):
  104. # append correction
  105. results.append({'correction': extract_text(correction)})
  106. # return results
  107. return results
  108. # get supported languages from their site
  109. def _fetch_supported_languages(resp):
  110. # response is a js file with regions as an embedded object
  111. response_page = resp.text
  112. response_page = response_page[response_page.find('regions:{') + 8:]
  113. response_page = response_page[:response_page.find('}') + 1]
  114. regions_json = loads(response_page)
  115. supported_languages = map((lambda x: x[3:] + '-' + x[:2].upper()), regions_json.keys())
  116. return list(supported_languages)