2009-03-31 3 views
14

私はPythonでGoogleのAJAX(JSON)Web Search APIを使用しようとしています。 Pythonのurllib.urlencode()はエンコードするために、文字列ではなく値のペアをとるため、私は立ち往生しています。 GoogleのAPIでは、クエリ文字列は検索用語であり、変数と関連付けません。URLはPythonで値以外のペアをエンコードします

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 

検索用語をどのようにすればいいですか?

答えて

36

代わりにurllib.quoteを探していると思います。

関連する問題