#!/usr/bin/env python # # google - Google search and list resulting URLs # # $Id$ import sys import os import argparse import re from googleapiclient.discovery import build argparser = argparse.ArgumentParser( description='Issue a Google search and return the URLs.') argparser.add_argument( '-n', type = int, default = 0, help = 'the number of items to return') argparser.add_argument( 'terms', nargs = '*', help = 'the search term(s)') args = argparser.parse_args() whitespace_rx = re.compile('\s+') if not 'GOOGLE_CSE' in os.environ: print '$GOOGLE_CSE must contain the Google Custom Search Engine id' exit(1) if not 'GOOGLE_KEY' in os.environ: print '$GOOGLE_KEY must contain the Google API key' exit(1) cse_id = '010321110373144430739:89ocwi6oarj' api_key = 'AIzaSyA52580jvQe6zfWrJzeF1jbcIRWKbfqnkE' def quote_if_spacey(term): if whitespace_rx.search(term): return "'" + term + "'" else: return term def google(num_results, terms): searchterms = ' '.join(map(quote_if_spacey, terms)) hits = [] try: cse = service = build( 'customsearch', 'v1', developerKey = api_key ).cse() if num_results > 0: l = cse.list( q = searchterms, cx = cse_id, num = num_results ) else: l = cse.list( q = searchterms, cx = cse_id ) hits = l.execute()['items'] except Exception, e: print 'Search failed: %s' % e exit(2) for h in hits: print h['link'] google(args.n, args.terms)