duckduckgo.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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 urllib import urlencode
  13. from lxml.html import fromstring
  14. from searx.engines.xpath import extract_text
  15. from searx.languages import language_codes
  16. # engine dependent config
  17. categories = ['general']
  18. paging = True
  19. language_support = True
  20. time_range_support = True
  21. # search-url
  22. url = 'https://duckduckgo.com/html?{query}&s={offset}'
  23. time_range_url = '&df={range}'
  24. time_range_dict = {'day': 'd',
  25. 'week': 'w',
  26. 'month': 'm'}
  27. # specific xpath variables
  28. result_xpath = '//div[@class="result results_links results_links_deep web-result "]' # noqa
  29. url_xpath = './/a[@class="result__a"]/@href'
  30. title_xpath = './/a[@class="result__a"]'
  31. content_xpath = './/a[@class="result__snippet"]'
  32. # do search-request
  33. def request(query, params):
  34. if params['time_range'] and params['time_range'] not in time_range_dict:
  35. return params
  36. offset = (params['pageno'] - 1) * 30
  37. if params['language'] == 'all':
  38. locale = None
  39. else:
  40. locale = params['language'].split('_')
  41. if len(locale) == 2:
  42. # country code goes first
  43. locale = locale[1].lower() + '-' + locale[0].lower()
  44. else:
  45. # tries to get a country code from language
  46. locale = locale[0].lower()
  47. lang_codes = [x[0] for x in language_codes]
  48. for lc in lang_codes:
  49. lc = lc.split('_')
  50. if locale == lc[0]:
  51. locale = lc[1].lower() + '-' + lc[0].lower()
  52. break
  53. if locale:
  54. params['url'] = url.format(
  55. query=urlencode({'q': query, 'kl': locale}), offset=offset)
  56. else:
  57. params['url'] = url.format(
  58. query=urlencode({'q': query}), offset=offset)
  59. if params['time_range'] in time_range_dict:
  60. params['url'] += time_range_url.format(range=time_range_dict[params['time_range']])
  61. return params
  62. # get response from search-request
  63. def response(resp):
  64. results = []
  65. doc = fromstring(resp.text)
  66. # parse results
  67. for r in doc.xpath(result_xpath):
  68. try:
  69. res_url = r.xpath(url_xpath)[-1]
  70. except:
  71. continue
  72. if not res_url:
  73. continue
  74. title = extract_text(r.xpath(title_xpath))
  75. content = extract_text(r.xpath(content_xpath))
  76. # append result
  77. results.append({'title': title,
  78. 'content': content,
  79. 'url': res_url})
  80. # return results
  81. return results