python - URL 在 Python 中编码一个非值对

标签 python json urlencode

我正在尝试在 Python 中使用 Google 的 AJAX (JSON) 网络搜索 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?

最佳答案

我认为您正在寻找 urllib.quote相反。

关于python - URL 在 Python 中编码一个非值对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/702986/

相关文章:

python - Pandas:将 JSON 列表值拆分为新列

java - response.sendRedirect 在 app2 中接收时用加密 URL 中的空格替换 +?

php - 如何在 PHP 中将 session 变量从一个域传递到另一个域

Python后台shell脚本通信

python - 这个简单的 python 元类有什么问题?

python - 用Nuitka编译任何Python程序后,我得到 “is not a valid win32 application”错误

python - 没有重复 child 的树

java - 使用键值对将 JSONObject 值转换为另一个 JSONObject

javascript - 从 Javascript-Object 生成表单

java - 无法在 groovy 中导入 java.net.URLEncoder