|
@@ -8,60 +8,71 @@
|
8
|
8
|
# @stable no
|
9
|
9
|
# @parse answer
|
10
|
10
|
|
11
|
|
-from re import search
|
|
11
|
+from re import search, sub
|
12
|
12
|
from json import loads
|
13
|
13
|
from urllib import urlencode
|
|
14
|
+from lxml import html
|
14
|
15
|
|
15
|
16
|
# search-url
|
16
|
17
|
url = 'http://www.wolframalpha.com/'
|
17
|
18
|
search_url = url+'input/?{query}'
|
18
|
|
-search_query = ''
|
|
19
|
+
|
|
20
|
+# xpath variables
|
|
21
|
+scripts_xpath = '//script'
|
|
22
|
+title_xpath = '//title'
|
|
23
|
+failure_xpath = '//p[attribute::class="pfail"]'
|
19
|
24
|
|
20
|
25
|
|
21
|
26
|
# do search-request
|
22
|
27
|
def request(query, params):
|
23
|
28
|
params['url'] = search_url.format(query=urlencode({'i': query}))
|
24
|
29
|
|
25
|
|
- # used in response
|
26
|
|
- global search_query
|
27
|
|
- search_query = query
|
28
|
|
-
|
29
|
30
|
return params
|
30
|
31
|
|
31
|
32
|
|
32
|
33
|
# get response from search-request
|
33
|
34
|
def response(resp):
|
34
|
35
|
results = []
|
35
|
|
- webpage = resp.text
|
36
|
36
|
line = None
|
37
|
37
|
|
|
38
|
+ dom = html.fromstring(resp.text)
|
|
39
|
+ scripts = dom.xpath(scripts_xpath)
|
|
40
|
+
|
38
|
41
|
# the answer is inside a js function
|
39
|
42
|
# answer can be located in different 'pods', although by default it should be in pod_0200
|
40
|
43
|
possible_locations = ['pod_0200\.push(.*)\n',
|
41
|
44
|
'pod_0100\.push(.*)\n']
|
42
|
45
|
|
|
46
|
+ # failed result
|
|
47
|
+ if dom.xpath(failure_xpath):
|
|
48
|
+ return results
|
|
49
|
+
|
43
|
50
|
# get line that matches the pattern
|
44
|
51
|
for pattern in possible_locations:
|
45
|
|
- try:
|
46
|
|
- line = search(pattern, webpage).group(1)
|
|
52
|
+ for script in scripts:
|
|
53
|
+ try:
|
|
54
|
+ line = search(pattern, script.text_content()).group(1)
|
|
55
|
+ break
|
|
56
|
+ except AttributeError:
|
|
57
|
+ continue
|
|
58
|
+ if line:
|
47
|
59
|
break
|
48
|
|
- except AttributeError:
|
49
|
|
- continue
|
50
|
60
|
|
51
|
61
|
if line:
|
52
|
62
|
# extract answer from json
|
53
|
63
|
answer = line[line.find('{'):line.rfind('}')+1]
|
54
|
64
|
answer = loads(answer.encode('unicode-escape'))
|
55
|
65
|
answer = answer['stringified'].decode('unicode-escape')
|
|
66
|
+ answer = sub(r'\\', '', answer)
|
56
|
67
|
|
57
|
68
|
results.append({'answer': answer})
|
58
|
69
|
|
59
|
|
- # failed result
|
60
|
|
- elif search('pfail', webpage):
|
61
|
|
- return results
|
|
70
|
+ # user input is in first part of title
|
|
71
|
+ title = dom.xpath(title_xpath)[0].text
|
|
72
|
+ result_url = request(title[:-16], {})['url']
|
62
|
73
|
|
63
|
74
|
# append result
|
64
|
|
- results.append({'url': request(search_query, {})['url'],
|
65
|
|
- 'title': search_query + ' - Wolfram|Alpha'})
|
|
75
|
+ results.append({'url': result_url,
|
|
76
|
+ 'title': title})
|
66
|
77
|
|
67
|
78
|
return results
|