Advertisement
elirang

2to3'ed googlecomp.py

Aug 16th, 2018
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.32 KB | None | 0 0
  1. #!/usr/bin/env python
  2. ################################
  3. # googlecomp.py ################
  4. # Get the first autocomplete ###
  5. # result of a Google search. ###
  6. # Dist. under the MIT License. #
  7. # ckjbgames 2017 ###############
  8. ################################
  9. import urllib.request, urllib.parse, urllib.error,json,sys,re
  10.  
  11. def firstautocomp(kw):
  12.     """
  13.    Get the first autocomplete result
  14.    for kw.
  15.    """
  16.     webpage="http://suggestqueries.google.com/complete/search?client=chrome&q="\
  17.              + urllib.parse.quote_plus(kw)
  18.     result=json.loads((urllib.request.urlopen(webpage).read()).decode('utf-8'))
  19.     if len(result[1]):
  20.         return result[1][0]
  21.     else:
  22.         return ''
  23.  
  24. def usage():
  25.     """
  26.    Show the usage of the program, then
  27.    exit with status 1.
  28.    """
  29.     sys.stderr.write("Usage: ./googlecomp.py keyword\n")
  30.     sys.stderr.write("\tFind the first Google autocomplete keyword.\n")
  31.     sys.stderr.write("\tkeyword: A keyword to find autocomplete results for.\n")
  32.     sys.exit(1)
  33.  
  34. if __name__ == '__main__':
  35.     if len(sys.argv) < 2:
  36.         usage()
  37.     else:
  38.         try:
  39.             print((firstautocomp(re.sub(r'\s','+',sys.argv[1]))))
  40.         except urllib.error.HTTPError as e:
  41.             sys.stderr.write("There was an HTTP error. Sorry about that.\n")
  42.             sys.exit(1)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement