Mar. 03, 2013

Google Command Line Script


Todays post will show how you can make a Google Command Line script with Python
(version 2.7.x)
Note: The Google Web Search API has been officially deprecated as of November 1,
2010. It will continue to work as per our deprecation policy, but the number of
requests you may make per day will be limited. Therefore, we encourage you to
move to the new Custom Search API.
To make a request to the Web search API, we have to import the modules that we

Loads the URL response

To make use of urlencode

Google returns JSON
Next we specify the URL for which we do the request too:
To make it a bit interactive, we will ask the user for an input and save the
result to a variable that we name "query".
query = raw_input("What do you want to search for ? >> ")
Create the response object by loading the the URL response, including the query
we asked for above. 
response = urllib2.urlopen (url + query ).read()
# Process the JSON string.
data = json.loads (response)

From this point we can play around with the results
Let's see the complete script
import urllib2
import urllib
import json

url = ""

query = raw_input("What do you want to search for ? >> ")

query = urllib.urlencode( {'q' : query } )

response = urllib2.urlopen (url + query ).read()

data = json.loads ( response )

results = data [ 'responseData' ] [ 'results' ]

for result in results:
    title = result['title']
    url = result['url']
    print ( title + '; ' + url )
Open an text editor , copy & paste the code above.

Save the file as and exit the editor.

Run the script:
$ python 
What do you want to search for ? >> python for beginners
BeginnersGuide - Python Wiki;
Python For Beginners;
Python For Beginners;

Share this article

Recommended Python Training – DataCamp

For Python training, our top recommendation is DataCamp.

Datacamp provides online interactive courses that combine interactive coding challenges with videos from top instructors in the field.

Datacamp has beginner to advanced Python training that programmers of all levels benefit from.


Download Our Free Guide To Learning Python

* indicates required

Read more about:
Disclosure of Material Connection: Some of the links in the post above are “affiliate links.” This means if you click on the link and purchase the item, I will receive an affiliate commission. Regardless, only recommend products or services that we try personally and believe will add value to our readers.