wolframalpha_noapi.py 1.6 KB

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