Created
May 31, 2012 14:53
-
-
Save srossross/2843941 to your computer and use it in GitHub Desktop.
Command Line Google Search
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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('>', '>') | |
strn = strn.replace('<', '<') | |
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)) | |
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