-
Notifications
You must be signed in to change notification settings - Fork 0
/
google_autosuggest.py
79 lines (63 loc) · 1.97 KB
/
google_autosuggest.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import xml.etree.ElementTree as ET
from collections import defaultdict
import requests
import time
def cal_exe_time(func, xml, want="all"):
start_time = time.time()
data = func(xml, want)
print(data)
print("time taken--- {} seconds ---".format(time.time() - start_time))
return data
def etree_to_dict(t):
d = {t.tag: {} if t.attrib else None}
children = list(t)
if children:
dd = defaultdict(list)
for dc in map(etree_to_dict, children):
for k, v in dc.items():
dd[k].append(v)
d = {t.tag: {k: v[0] if len(v) == 1 else v for k, v in dd.items()}}
if t.attrib:
d[t.tag].update(('@' + k, v) for k, v in t.attrib.items())
if t.text:
text = t.text.strip()
if children or t.attrib:
if text:
d[t.tag]['#text'] = text
else:
d[t.tag] = text
return d
def find_sugg(myroot, w="all"):
data = []
count = 0
for root in myroot:
for x in root:
if w != "all":
if count >= w:
break
data.append(x.attrib["data"])
count += 1
return data
def find_data(myroot, w="all"):
response = etree_to_dict(myroot)
data = []
datalist = response["toplevel"]["CompleteSuggestion"]
count = 0
for x in datalist:
if w != "all":
if count >= w:
break
data.append(x["suggestion"]["@data"])
count += 1
return data
def fetch_suggestions(query):
x = requests.get('https://www.google.com/complete/search?output=toolbar&q={}&hl=en'.format(query))
data = x.text
myroot = ET.fromstring(data)
return myroot
xml = fetch_suggestions("github")
# extraction starts here
# method 1 by converting xml to dict
cal_exe_time(find_data, xml, "all")
# method 2 by direct putting data to list
cal_exe_time(find_sugg, xml, 3)