This repository has been archived by the owner on Jan 15, 2021. It is now read-only.
forked from henux/cli-google
-
Notifications
You must be signed in to change notification settings - Fork 1
/google
executable file
·212 lines (193 loc) · 6.51 KB
/google
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python3
#
# Copyright (C) 2008 Henri Hakkinen
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import termios, fcntl, struct
import webbrowser
import html.parser
from urllib.parse import quote_plus
from http.client import HTTPSConnection
from getopt import getopt, GetoptError
# Global variables
columns = None # Terminal window size.
start = None # The first result to display (option -s)
num = None # Number of results to display (option -n)
lang = None # Language to search for (option -l)
openUrl = False # If True, opens the first URL in browser (option -j)
colorize = False # If True, colorizes the output (option -C)
# Classes
class GoogleParser(html.parser.HTMLParser):
def __init__(self):
html.parser.HTMLParser.__init__(self)
self.handle_starttag = self.main_start
self.handle_data = self.main_data
self.handle_endtag = self.main_end
def main_start(self, tag, attrs):
if tag == "li" and len(attrs) > 0 and attrs[0] == ("class", "g"):
self.title = ""
self.url = ""
self.text = ""
self.handle_starttag = self.li_start
self.handle_data = self.li_data
self.handle_endtag = self.li_end
def main_data(self, data):
pass
def main_end(self, tag):
pass
# <li class="g"> ... </li>
def li_start(self, tag, attrs):
if tag == "h3":
self.handle_starttag = self.h3_start
self.handle_data = self.h3_data
self.handle_endtag = self.h3_end
elif tag == "div":
self.handle_starttag = self.div_start
self.handle_data = self.div_data
self.handle_endtag = self.div_end
def li_data(self, data):
pass
def li_end(self, tag):
if tag == "div":
print_entry(self.title, self.url, self.text)
self.handle_starttag = self.main_start
self.handle_data = self.main_data
self.handle_endtag = self.main_end
# <h3> ... </h3>
def h3_start(self, tag, attrs):
if tag == "a":
self.url = attrs[0][1]
def h3_data(self, data):
self.title += data
def h3_end(self, tag):
if tag == "h3":
self.handle_starttag = self.li_start
self.handle_data = self.li_data
self.handle_endtag = self.li_end
# <div> ... </div>
def div_start(self, tag, start):
if tag == "br":
self.handle_starttag = self.li_start
self.handle_data = self.li_data
self.handle_endtag = self.li_end
def div_data(self, data):
self.text += data
def div_end(self, tag):
pass
# Functions
def connect(body):
connection = HTTPSConnection("www.google.com")
connection.request("GET", body)
response = connection.getresponse()
return connection, response
def print_entry(title, url, text):
# Open the URL in a web browser if option -j was specified.
if openUrl:
webbrowser.open(url)
sys.exit(0)
# Print the title and the URL.
if colorize:
print("\x1B[96m* \x1B[92m%s\n\x1B[93m%s\x1B[39m" % (title, url))
else:
print("* %s\n%s" % (title, url))
# Print the text with truncating.
col = 0
for w in text.split():
if (col + len(w) + 1) > columns:
col = 0
print()
print(w, end=' ')
col += len(w) + 1
print("\n")
def usage():
print("Usage: google [OPTIONS] KEYWORDS...")
print("Performs a Google search and prints the results to stdout.\n")
print("Options")
print(" -s N start at the Nth result")
print(" -n N show N results")
print(" -l LANG display in language LANG, such as fi for Finnish")
print(" -C enable color output")
print(" -j open the first result in a web browser\n")
print("Copyright (C) 2008 Henri Hakkinen.")
print("Report bugs to <[email protected]>.")
sys.exit(1)
########### Program Main
# Process command line options.
optlist = None
keywords = None
if len(sys.argv) < 2:
usage()
try:
optlist, keywords = getopt(sys.argv[1:], "s:n:l:Cj")
for opt in optlist:
if opt[0] == "-s":
# Option -s N
if not opt[1].isdigit():
print("google: option -s needs an integer")
sys.exit(1)
start = opt[1]
elif opt[0] == "-n":
# Option -n N
if not opt[1].isdigit():
print("google: option -n needs an integer")
sys.exit(1)
num = opt[1]
elif opt[0] == "-l":
# Option -l LANG
lang = opt[1]
elif opt[0] == "-C":
# Option -C
colorize = True
elif opt[0] == "-j":
# Option -j
openUrl = True
if len(keywords) < 1:
usage()
except GetoptError as e:
print("google:", e)
sys.exit(1)
# Construct the query URL.
url = "/search?&ie=UTF-8&oe=UTF-8&"
if start != None:
url += "start=" + start + "&"
if num != None:
url += "num=" + num + "&"
if lang != None:
url += "hl=" + lang + "&"
url += "q=" + quote_plus(keywords[0])
for kw in keywords[1:]:
url += "+" + quote_plus(kw)
if not openUrl:
print("\nhttps://www.google.com%s\n" % url)
# Get the terminal window size.
winsz = fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ, "1234")
columns = struct.unpack("HH", winsz)[1]
# Connect to Google and request the result page.
conn, resp = connect(url)
# Check for redirects
while resp.status == 301 or resp.status == 302:
loc = resp.getheader('Location')
conn.close()
print("Redirected to:", loc)
conn, resp = connect(loc)
if resp.status != 200:
# The server responded with an error.
print("Server responded with an error:", str(resp.status))
sys.exit(1)
# Parse the HTML document and print the results.
parser = GoogleParser()
parser.feed(resp.read().decode('utf-8'))
conn.close()
# vim:set sts=4 sw=4 et: