URL 在 Python 中对非值对进行编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/702986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:41:32  来源:igfitidea点击:

URL encode a non-value pair in Python

pythonjsonurlencode

提问by Dan

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.

我正在尝试在 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

How do I urlencode my search terms?

我如何对我的搜索词进行 urlencode?

回答by Ben Blank

I think you're looking for urllib.quoteinstead.

我认为你正在寻找urllib.quote