autocomplete.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. '''
  2. searx is free software: you can redistribute it and/or modify
  3. it under the terms of the GNU Affero General Public License as published by
  4. the Free Software Foundation, either version 3 of the License, or
  5. (at your option) any later version.
  6. searx is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  9. GNU Affero General Public License for more details.
  10. You should have received a copy of the GNU Affero General Public License
  11. along with searx. If not, see < http://www.gnu.org/licenses/ >.
  12. (C) 2013- by Adam Tauber, <asciimoo@gmail.com>
  13. '''
  14. from lxml import etree
  15. from requests import get
  16. from json import loads
  17. from urllib import urlencode
  18. def dbpedia(query):
  19. # dbpedia autocompleter
  20. autocomplete_url = 'http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?' # noqa
  21. response = get(autocomplete_url
  22. + urlencode(dict(QueryString=query)))
  23. results = []
  24. if response.ok:
  25. dom = etree.fromstring(response.content)
  26. results = dom.xpath('//a:Result/a:Label//text()',
  27. namespaces={'a': 'http://lookup.dbpedia.org/'})
  28. return results
  29. def duckduckgo(query):
  30. # duckduckgo autocompleter
  31. url = 'https://ac.duckduckgo.com/ac/?{0}&type=list'
  32. resp = loads(get(url.format(urlencode(dict(q=query)))).text)
  33. if len(resp) > 1:
  34. return resp[1]
  35. return []
  36. def google(query):
  37. # google autocompleter
  38. autocomplete_url = 'http://suggestqueries.google.com/complete/search?client=toolbar&' # noqa
  39. response = get(autocomplete_url
  40. + urlencode(dict(q=query)))
  41. results = []
  42. if response.ok:
  43. dom = etree.fromstring(response.text)
  44. results = dom.xpath('//suggestion/@data')
  45. return results
  46. def wikipedia(query):
  47. # wikipedia autocompleter
  48. url = 'https://en.wikipedia.org/w/api.php?action=opensearch&{0}&limit=10&namespace=0&format=json' # noqa
  49. resp = loads(get(url.format(urlencode(dict(search=query)))).text)
  50. if len(resp) > 1:
  51. return resp[1]
  52. return []
  53. backends = {'dbpedia': dbpedia,
  54. 'duckduckgo': duckduckgo,
  55. 'google': google,
  56. 'wikipedia': wikipedia
  57. }