Created
April 23, 2017 20:00
-
-
Save ckjbgames/f7bfa353e639f4a449fc57ab0a7befd3 to your computer and use it in GitHub Desktop.
Get the first Google autocomplete result of a search.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
################################ | |
# googlecomp.py ################ | |
# Get the first autocomplete ### | |
# result of a Google search. ### | |
# Dist. under the MIT License. # | |
# ckjbgames 2017 ############### | |
################################ | |
import urllib2,json,sys,re | |
def firstautocomp(kw): | |
""" | |
Get the first autocomplete result | |
for kw. | |
""" | |
webpage="http://suggestqueries.google.com/complete/search?client=chrome&q="\ | |
+kw | |
result=json.loads(urllib2.urlopen(webpage).read()) | |
if len(result[1]): | |
return result[1][0] | |
else: | |
return '' | |
def usage(): | |
""" | |
Show the usage of the program, then | |
exit with status 1. | |
""" | |
sys.stderr.write("Usage: ./googlecomp.py keyword\n") | |
sys.stderr.write("\tFind the first Google autocomplete keyword.\n") | |
sys.stderr.write("\tkeyword: A keyword to find autocomplete results for.\n") | |
sys.exit(1) | |
if __name__ == '__main__': | |
if len(sys.argv) < 2: | |
usage() | |
else: | |
try: | |
print firstautocomp(re.sub(r'\s','+',sys.argv[1])) | |
except urllib2.HTTPError as e: | |
sys.stderr.write("There was an HTTP error. Sorry about that.\n") | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment