#!/usr/local/bin/python

import re
import sys
from SOAPpy import SOAPProxy
from SOAPpy import Types
from SOAPpy import Errors

YOUR_GOOGLEAPI_KEY=''

def GoogleSearch(query):
  """Import SOAPpy, and use the Google Web API's to search for results. The
  search returns only the first result. The URL of the result as well at the
  snippet are then printed back to the user.
  Some of this code was borrowed from an IBM developerworks library:
  http://www-128.ibm.com/developerworks/webservices/library/ws-pyth14/
  under the Big Blue Open License:
  http://www-128.ibm.com/developerworks/library/os-ipl.html
  """ 

  if YOUR_GOOGLEAPI_KEY == 'None':
    return 'You forgot to add your Google API key to googlesearch.py!'

  # CONSTANTS
  _url = 'http://api.google.com/search/beta2'
  _namespace = 'urn:GoogleSearch'
              
  # need to marshall into SOAP types
  SOAP_FALSE = Types.booleanType(0)
  SOAP_TRUE = Types.booleanType(1)

  # create SOAP proxy object
  google = SOAPProxy(_url, _namespace)

  # Google search options
  _license_key = YOUR_GOOGLEAPI_KEY
  _start = 0
  _maxResults = 1
  _filter = SOAP_FALSE
  _restrict = ''
  _safeSearch = SOAP_FALSE
  _lang_restrict = ''

  # call search method over SOAP proxy
  try:
    results = google.doGoogleSearch(_license_key, query,
                                    _start, _maxResults,
                                    _filter, _restrict,
                                    _safeSearch, _lang_restrict,
                                    '', '' )
    numresults = len(results.resultElements)
    for i in range(numresults):
      title = results.resultElements[i].title
      url = results.resultElements[i].URL
      snippet = results.resultElements[i].snippet
      #noh_title = title.replace('<b>', '').replace('</b>', '')
      p_tags = re.compile('(<.*?>)')
      p_ents = re.compile('(&.*;?)')
      title = p_tags.sub('', title)
      title = p_ents.sub('', title)
      snippet = p_tags.sub('', snippet)
      snippet = p_ents.sub('', snippet)
      searchresult = '%s: %s, %s' % (title,url,snippet)
      return searchresult.encode('utf_8')
  except Errors.HTTPError:
    searchresult = sys.exc_info[1]
    print searchresult
    return 'There was a problem with your query'

if __name__ == "__main__":
  import sys
  try:
    sys.argv[1]
  except IndexError:
    print 'Usage: googlesearch.py "<query>"'
    sys.exit(1)
  result = GoogleSearch(sys.argv[1])
  print result
