googlecomp.py: The Complete Google Autocomplete Script

by ckjbgames

So I saw an article in 34:1 about Google's autocomplete and how you can find funny (and not-so-funny) autocomplete results for politicians, et cetera.

That got my brain going.  I started writing.  A little bit of coding later, I wrote this little bit of a program.  It takes command-line arguments and can thus be used in a shell script.

If anyone has any practical use for this little script, other than for giggles, or how it could be improved, please tell me what it is in the 2600 letters section.

#!/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)

Code: googlecomp.py

Return to $2600 Index