Python Google Command Line Script


SUBMITTED BY: alemotta

DATE: March 15, 2017, 6:07 p.m.

FORMAT: Text only

SIZE: 1.9 kB

HITS: 387

  1. Python Google Command Line Script
  2. Overview
  3. Todays post will show how you can make a Google Command Line script with Python
  4. (version 2.7.x)
  5. """
  6. Note: The Google Web Search API has been officially deprecated as of November 1,
  7. 2010. It will continue to work as per our deprecation policy, but the number of
  8. requests you may make per day will be limited. Therefore, we encourage you to
  9. move to the new Custom Search API.
  10. """
  11. To make a request to the Web search API, we have to import the modules that we
  12. need.
  13. urllib2
  14. Loads the URL response
  15. urllib
  16. To make use of urlencode
  17. json
  18. Google returns JSON
  19. Next we specify the URL for which we do the request too:
  20. http://ajax.googleapis.com/ajax/services/search/web?v=1.0&
  21. To make it a bit interactive, we will ask the user for an input and save the
  22. result to a variable that we name "query".
  23. query = raw_input("What do you want to search for ? >> ")
  24. Create the response object by loading the the URL response, including the query
  25. we asked for above.
  26. response = urllib2.urlopen (url + query ).read()
  27. # Process the JSON string.
  28. data = json.loads (response)
  29. From this point we can play around with the results
  30. GoogleSearch.py
  31. Let's see the complete script
  32. import urllib2
  33. import urllib
  34. import json
  35. url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
  36. query = raw_input("What do you want to search for ? >> ")
  37. query = urllib.urlencode( {'q' : query } )
  38. response = urllib2.urlopen (url + query ).read()
  39. data = json.loads ( response )
  40. results = data [ 'responseData' ] [ 'results' ]
  41. for result in results:
  42. title = result['title']
  43. url = result['url']
  44. print ( title + '; ' + url )
  45. Open an text editor , copy & paste the code above.
  46. Save the file as GoogleSearch.py and exit the editor.
  47. Run the script:
  48. $ python searchGoogle.py

comments powered by Disqus