Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL encode a non-value pair in Python

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?

like image 804
Dan Avatar asked Mar 31 '09 20:03

Dan


People also ask

How do you pass special characters in a URL in Python?

s = urllib2. quote(s) # URL encode. # Now "s" is encoded the way you need it. It works!

How do you encode a URL parameter in Python?

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.

What does Urllib parse Urlencode do?

parse. urlencode() method can be used for generating the query string of a URL or data for a POST request.

How do I import Urlencode into Python?

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.


1 Answers

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

like image 131
Ben Blank Avatar answered Oct 05 '22 12:10

Ben Blank