duckduckgo.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. @todo language support
  12. (the current used site does not support language-change)
  13. """
  14. from urllib import urlencode
  15. from lxml.html import fromstring
  16. from searx.engines.xpath import extract_text
  17. # engine dependent config
  18. categories = ['general']
  19. paging = True
  20. language_support = True
  21. # search-url
  22. url = 'https://duckduckgo.com/html?{query}&s={offset}'
  23. # specific xpath variables
  24. result_xpath = '//div[@class="results_links results_links_deep web-result"]' # noqa
  25. url_xpath = './/a[@class="large"]/@href'
  26. title_xpath = './/a[@class="large"]'
  27. content_xpath = './/div[@class="snippet"]'
  28. # do search-request
  29. def request(query, params):
  30. offset = (params['pageno'] - 1) * 30
  31. if params['language'] == 'all':
  32. locale = 'en-us'
  33. else:
  34. locale = params['language'].replace('_', '-').lower()
  35. params['url'] = url.format(
  36. query=urlencode({'q': query, 'kl': locale}),
  37. offset=offset)
  38. return params
  39. # get response from search-request
  40. def response(resp):
  41. results = []
  42. doc = fromstring(resp.text)
  43. # parse results
  44. for r in doc.xpath(result_xpath):
  45. try:
  46. res_url = r.xpath(url_xpath)[-1]
  47. except:
  48. continue
  49. if not res_url:
  50. continue
  51. title = extract_text(r.xpath(title_xpath))
  52. content = extract_text(r.xpath(content_xpath))
  53. # append result
  54. results.append({'title': title,
  55. 'content': content,
  56. 'url': res_url})
  57. # return results
  58. return results