duckduckgo.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. language_support = True
  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. if params['language'] == 'all':
  31. locale = 'en-us'
  32. else:
  33. locale = params['language'].replace('_','-').lower()
  34. params['url'] = url.format(
  35. query=urlencode({'q': query, 'kl': locale}),
  36. offset=offset)
  37. return params
  38. # get response from search-request
  39. def response(resp):
  40. results = []
  41. doc = fromstring(resp.text)
  42. # parse results
  43. for r in doc.xpath(result_xpath):
  44. try:
  45. res_url = r.xpath(url_xpath)[-1]
  46. except:
  47. continue
  48. if not res_url:
  49. continue
  50. title = html_to_text(''.join(r.xpath(title_xpath)))
  51. content = html_to_text(''.join(r.xpath(content_xpath)))
  52. # append result
  53. results.append({'title': title,
  54. 'content': content,
  55. 'url': res_url})
  56. # return results
  57. return results