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?
s = urllib2. quote(s) # URL encode. # Now "s" is encoded the way you need it. It works!
You can encode multiple parameters at once using urllib. parse. urlencode() function. This is a convenience function which takes a dictionary of key value pairs or a sequence of two-element tuples and uses the quote_plus() function to encode every value.
parse. urlencode() method can be used for generating the query string of a URL or data for a POST request.
URL Encode a Dictionary Using urlencode() in Python In the following code, we have to import the urlib library, and we will pass our query string to the urlencode() function of the parse module of the urlib library. In the output, we will get the required encoded URL.
I think you're looking for urllib.quote
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With