wolframalpha_noapi.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # WolframAlpha (Maths)
  2. #
  3. # @website http://www.wolframalpha.com/
  4. #
  5. # @using-api no
  6. # @results HTML
  7. # @stable no
  8. # @parse answer
  9. from re import search
  10. from json import loads
  11. from urllib import urlencode
  12. # search-url
  13. url = 'http://www.wolframalpha.com/'
  14. search_url = url+'input/?{query}'
  15. # do search-request
  16. def request(query, params):
  17. params['url'] = search_url.format(query=urlencode({'i': query}))
  18. return params
  19. # get response from search-request
  20. def response(resp):
  21. results = []
  22. webpage = resp.text
  23. line = None
  24. # the answer is inside a js function
  25. # answer can be located in different 'pods', although by default it should be in pod_0200
  26. possible_locations = ['pod_0200\.push(.*)\n',
  27. 'pod_0100\.push(.*)\n']
  28. # get line that matches the pattern
  29. for pattern in possible_locations:
  30. try:
  31. line = search(pattern, webpage).group(1)
  32. break
  33. except AttributeError:
  34. continue
  35. if not line:
  36. return results
  37. # extract answer from json
  38. answer = line[line.find('{'):line.rfind('}')+1]
  39. answer = loads(answer.encode('unicode-escape'))
  40. answer = answer['stringified'].decode('unicode-escape')
  41. results.append({'answer': answer})
  42. return results