Skip to content

Instantly share code, notes, and snippets.

@srossross
Created May 31, 2012 14:53
Show Gist options
  • Save srossross/2843941 to your computer and use it in GitHub Desktop.
Save srossross/2843941 to your computer and use it in GitHub Desktop.
Command Line Google Search
import urllib2
import json
import textwrap
def google_search(search_string):
google= 'http://ajax.googleapis.com/ajax/services/search'
msg = urllib2.quote(search_string)
soc = urllib2.urlopen('{google}/web?v=1.0&q={msg}'.format(google=google, msg=msg))
text = soc.read()
model = json.loads(text)
if model['responseStatus'] != 200:
raise urllib2.HTTPError(model['responseDetails'])
return model['responseData']['results']
def unhtml(strn):
strn = strn.replace(''',"'")
strn = strn.replace('"','"')
strn = strn.replace('<b>', '')
strn = strn.replace('</b>', '')
strn = strn.replace('&gt', '>')
strn = strn.replace('&lt', '<')
return strn
def print_result(result):
title = unhtml(result['titleNoFormatting'])
print title
print '=' * len(title)
print str(result['url'])
print '-' * len(title)
text = unhtml(result['content'])
print '\n'.join(textwrap.wrap(text, len(title) + 10))
print
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('search_string')
args = parser.parse_args()
results = google_search(args.search_string)
for result in results:
print_result(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment