views:

3387

answers:

1

I'm trying to use Google's AJAX (JSON) Web Search API in Python. I'm stuck because Python's urllib.urlencode() only takes value pairs, not strings by themselves, to encode. In Google's API, the query string is the search term and it doesn't associate with a variable.

query = "string that needs to be encoded"
params = urllib.urlencode(query) # THIS FAILS
# http://code.google.com/apis/ajaxsearch/documentation/reference.html
url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&%s&%s" % (params, GOOGLE_API_KEY)

request = urllib2.Request(url)
request.add_header('Referer', GOOGLE_REFERER)

search_results = urllib2.urlopen(request)
raw_results = search_results.read()
json = simplejson.loads(raw_results)
estimatedResultCount = json['responseData']['cursor']['estimatedResultCount']

if estimatedResultCount != 0:
    print "Google: %s hits" % estimatedResultCount

How do I urlencode my search terms?

+15  A: 

I think you're looking for urllib.quote instead.

Ben Blank