Skip to content

Instantly share code, notes, and snippets.

@ckjbgames
Created April 23, 2017 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckjbgames/f7bfa353e639f4a449fc57ab0a7befd3 to your computer and use it in GitHub Desktop.
Save ckjbgames/f7bfa353e639f4a449fc57ab0a7befd3 to your computer and use it in GitHub Desktop.
Get the first Google autocomplete result of a search.
#!/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