duckduckgo.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. ## DuckDuckGo (Web)
  2. #
  3. # @website https://duckduckgo.com/
  4. # @provide-api yes (https://duckduckgo.com/api), but not all results from search-site
  5. #
  6. # @using-api no
  7. # @results HTML (using search portal)
  8. # @stable no (HTML can change)
  9. # @parse url, title, content
  10. #
  11. # @todo rewrite to api
  12. # @todo language support (the current used site does not support language-change)
  13. from urllib import urlencode
  14. from lxml.html import fromstring
  15. from searx.utils import html_to_text
  16. # engine dependent config
  17. categories = ['general']
  18. paging = True
  19. locale = 'us-en'
  20. # search-url
  21. url = 'https://duckduckgo.com/html?{query}&s={offset}'
  22. # specific xpath variables
  23. result_xpath = '//div[@class="results_links results_links_deep web-result"]' # noqa
  24. url_xpath = './/a[@class="large"]/@href'
  25. title_xpath = './/a[@class="large"]//text()'
  26. content_xpath = './/div[@class="snippet"]//text()'
  27. # do search-request
  28. def request(query, params):
  29. offset = (params['pageno'] - 1) * 30
  30. params['url'] = url.format(
  31. query=urlencode({'q': query, 'l': locale}),
  32. offset=offset)
  33. return params
  34. # get response from search-request
  35. def response(resp):
  36. results = []
  37. doc = fromstring(resp.text)
  38. # parse results
  39. for r in doc.xpath(result_xpath):
  40. try:
  41. res_url = r.xpath(url_xpath)[-1]
  42. except:
  43. continue
  44. if not res_url:
  45. continue
  46. title = html_to_text(''.join(r.xpath(title_xpath)))
  47. content = html_to_text(''.join(r.xpath(content_xpath)))
  48. # append result
  49. results.append({'title': title,
  50. 'content': content,
  51. 'url': res_url})
  52. # return results
  53. return results