duckduckgo.py 4.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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. # engine dependent config
  18. categories = ['general']
  19. paging = True
  20. language_support = True
  21. supported_languages_url = 'https://duckduckgo.com/d2030.js'
  22. time_range_support = True
  23. # search-url
  24. url = 'https://duckduckgo.com/html?{query}&s={offset}&api=/d.js&o=json&dc={dc_param}'
  25. time_range_url = '&df={range}'
  26. time_range_dict = {'day': 'd',
  27. 'week': 'w',
  28. 'month': 'm'}
  29. # specific xpath variables
  30. result_xpath = '//div[@class="result results_links results_links_deep web-result "]' # noqa
  31. url_xpath = './/a[@class="result__a"]/@href'
  32. title_xpath = './/a[@class="result__a"]'
  33. content_xpath = './/a[@class="result__snippet"]'
  34. # match query's language to a region code that duckduckgo will accept
  35. def get_region_code(lang, lang_list=None):
  36. # custom fixes for languages
  37. if lang == 'all':
  38. region_code = None
  39. elif lang[:2] == 'ja':
  40. region_code = 'jp-jp'
  41. elif lang[:2] == 'sl':
  42. region_code = 'sl-sl'
  43. elif lang == 'zh-TW':
  44. region_code = 'tw-tzh'
  45. elif lang == 'zh-HK':
  46. region_code = 'hk-tzh'
  47. elif lang[-2:] == 'SA':
  48. region_code = 'xa-' + lang.split('-')[0]
  49. elif lang[-2:] == 'GB':
  50. region_code = 'uk-' + lang.split('-')[0]
  51. else:
  52. region_code = lang.split('-')
  53. if len(region_code) == 2:
  54. # country code goes first
  55. region_code = region_code[1].lower() + '-' + region_code[0].lower()
  56. else:
  57. # tries to get a country code from language
  58. region_code = region_code[0].lower()
  59. for lc in (lang_list or supported_languages):
  60. lc = lc.split('-')
  61. if region_code == lc[0]:
  62. region_code = lc[1].lower() + '-' + lc[0].lower()
  63. break
  64. return region_code
  65. # do search-request
  66. def request(query, params):
  67. if params['time_range'] and params['time_range'] not in time_range_dict:
  68. return params
  69. offset = (params['pageno'] - 1) * 30
  70. region_code = get_region_code(params['language'])
  71. if region_code:
  72. params['url'] = url.format(
  73. query=urlencode({'q': query, 'kl': region_code}), offset=offset, dc_param=offset)
  74. else:
  75. params['url'] = url.format(
  76. query=urlencode({'q': query}), offset=offset, dc_param=offset)
  77. if params['time_range'] in time_range_dict:
  78. params['url'] += time_range_url.format(range=time_range_dict[params['time_range']])
  79. return params
  80. # get response from search-request
  81. def response(resp):
  82. results = []
  83. doc = fromstring(resp.text)
  84. # parse results
  85. for r in doc.xpath(result_xpath):
  86. try:
  87. res_url = r.xpath(url_xpath)[-1]
  88. except:
  89. continue
  90. if not res_url:
  91. continue
  92. title = extract_text(r.xpath(title_xpath))
  93. content = extract_text(r.xpath(content_xpath))
  94. # append result
  95. results.append({'title': title,
  96. 'content': content,
  97. 'url': res_url})
  98. # return results
  99. return results
  100. # get supported languages from their site
  101. def _fetch_supported_languages(resp):
  102. # response is a js file with regions as an embedded object
  103. response_page = resp.text
  104. response_page = response_page[response_page.find('regions:{') + 8:]
  105. response_page = response_page[:response_page.find('}') + 1]
  106. regions_json = loads(response_page)
  107. supported_languages = map((lambda x: x[3:] + '-' + x[:2].upper()), regions_json.keys())
  108. return list(supported_languages)