duckduckgo.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. offset = (params['pageno'] - 1) * 30
  35. if params['language'] == 'all':
  36. locale = None
  37. else:
  38. locale = params['language'].split('_')
  39. if len(locale) == 2:
  40. # country code goes first
  41. locale = locale[1].lower() + '-' + locale[0].lower()
  42. else:
  43. # tries to get a country code from language
  44. locale = locale[0].lower()
  45. lang_codes = [x[0] for x in language_codes]
  46. for lc in lang_codes:
  47. lc = lc.split('_')
  48. if locale == lc[0]:
  49. locale = lc[1].lower() + '-' + lc[0].lower()
  50. break
  51. if locale:
  52. params['url'] = url.format(
  53. query=urlencode({'q': query, 'kl': locale}), offset=offset)
  54. else:
  55. params['url'] = url.format(
  56. query=urlencode({'q': query}), offset=offset)
  57. if params['time_range'] in time_range_dict:
  58. params['url'] += time_range_url.format(range=time_range_dict[params['time_range']])
  59. return params
  60. # get response from search-request
  61. def response(resp):
  62. results = []
  63. doc = fromstring(resp.text)
  64. # parse results
  65. for r in doc.xpath(result_xpath):
  66. try:
  67. res_url = r.xpath(url_xpath)[-1]
  68. except:
  69. continue
  70. if not res_url:
  71. continue
  72. title = extract_text(r.xpath(title_xpath))
  73. content = extract_text(r.xpath(content_xpath))
  74. # append result
  75. results.append({'title': title,
  76. 'content': content,
  77. 'url': res_url})
  78. # return results
  79. return results