16

Python で Google の AJAX (JSON) Web Search 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 するにはどうすればよいですか?

4

1 に答える 1

37

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

于 2009-03-31T20:52:33.887 に答える