我正在尝试在Python中使用Google的AJAX(JSON)Web搜索API。我被卡住了,因为Python的urllib.urlencode()只接受值对而不是字符串来进行编码。在Google的API中,查询字符串是搜索字词,它不与变量关联。
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
如何对我的搜索字词进行urlencode? p>